Created two threads in my class , one thread for to display even numbers and second thread for to display odd numbers. But my result would be 1 2 3 4 5 6 7 8 9 10............solution through producer consumer problem

package com.secondpackage;

public class ProducerConsumerTest {
public static void main(String[] args) {
System.out.println("ProducerConsumerTest main is calling");
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}

class CubbyHole {
private int contents;
private boolean available = false;

public synchronized int get() {
System.out.println("CubbyHole get is calling");
while (available == false) {
try {
wait();
} catch (InterruptedException e) {
}
}
available = false;
notifyAll();
System.out.println("CubbyHole get contents is "+contents);
return contents;
}

public synchronized void put(int value) {
System.out.println("CubbyHole put is calling value is "+value);
while (available == true) {
try {
wait();
} catch (InterruptedException e) {
}
}
contents = value;
System.out.println("CubbyHole put is calling contents is "+contents);
available = true;
notifyAll();
}
}

class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;

public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
System.out.println("Consumer con is calling number is "+number);
}

public void run() {
System.out.println("Consumer run() is calling ");
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get();
System.out.println("Consumer #" + this.number + " got: " + value);
}
}
}

class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;

public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
System.out.println("Producer con is calling number is "+number);
}

public void run() {
System.out.println("Producer run() is calling ");
for (int i = 0; i < 10; i++) {
cubbyhole.put(i);
System.out.println("Producer #" + this.number + " put: " + i);
try {
sleep((int) (Math.random() * 100));
} catch (InterruptedException e) {
}
}
}
}

Comments

Popular posts from this blog

Android Objective type Question and Answers

Android Questions and Answers for written exams

Core Java -----Question and Answers