Hi Kishan,
I thought the
Java API has cheated me, when u told the above code is working !!!
-----------
public void consume(producer b) {
for(int i = 0;i<20;i++) {
synchronized(b) {
try {
while(!b.flag) {
System.out.println("waiting");
/////// Can't be !!! U did not acquire the lock for Consumer object
this.wait();
}
b.flag = false;
System.out.println("Got " + b.a);
b.notify();
Thread.sleep(1000);
} catch(InterruptedException e) {
System.out.println("Interrupted eception caught in consumer");
}
--------------
Did u noticed that the message in the while loop is not executing ???
--------------
Modify that code by removing the while loop, then execute the code !!! i mean like this
//while(!b.flag) {
this.wait();
//}
-------------
Then put the original while loop back, and comment the Thread.sleep() method from both the classes !!
-------------
I modifed ur code, try this out ..
------------
import java.util.*;
class producer implements Runnable{
public int a;
public boolean flag = false;
public synchronized void produce() {
for(int index = 0; index < 5; index++) {
try {
while(flag == true) {
System.out.println("Producer waiting ..");
wait();
}
a = (new Random()).nextInt();
flag = true;
System.out.println("produced " + a);
notifyAll();
} catch (InterruptedException e) {
System.out.println("Interrupted eception caught in producer");
}
}
}
public void run() {
produce();
}
}
class consumer implements Runnable {
producer ab;
public consumer(producer pr) {
ab = pr;
}
public void consume(producer b) {
for(int i = 0;i<5;i++) {
synchronized(b) {
try {
while(b.flag == false) {
System.out.println("Consumer waiting ...");
b.wait();
}
b.flag = false;
System.out.println("Got " + b.a);
b.notifyAll();
} catch(InterruptedException e) {
System.out.println("Interrupted eception caught in consumer");
}
}
}
}
public void run() {
consume(ab);
}
}
class prodcons {
public static void main(
String args[]) {
producer p;
Thread tp = new Thread((p = new producer()));
Thread tc = new Thread(new consumer(p));
tc.setPriority(Thread.MAX_PRIORITY);
tp.setPriority(Thread.MIN_PRIORITY);
tp.start();
tc.start();
}
}
-----------
[This message has been edited by Jon Aryan (edited October 12, 2000).]
[This message has been edited by Jon Aryan (edited October 12, 2000).]