Monday 15 April 2013

java - Thread is not acquiring monitor after notify calls -



java - Thread is not acquiring monitor after notify calls -

i made 1 producer , 1 consumer thread. when list empty consumer went waiting state, producer insert item in list , calls notify() invoke consumer thread consumer not invoking. remains in waiting state.

code have tried is:

package xs; import java.util.arraylist; import java.util.date; import java.util.list; public class testmain { public static void main(string[] args) { product pro = new product(); producer produce = new producer(pro); consumer consume = new consumer(pro); thread thr1 = new thread(produce, "producer"); thread thr2 = new thread(consume, "consumer"); thr1.start(); thr2.start(); } } class product{ list<date> list; public product() { list = new arraylist<date>(); } public void produce(date i){ list.add(i); } public date consume(){ homecoming list.remove(0); } } class producer implements runnable{ product product; @override public void run() { while(true){ synchronized (this) { while(product.list.size() == 2){ seek { wait(); } grab (interruptedexception e) { // todo auto-generated grab block e.printstacktrace(); } } product.produce(new date()); system.out.println("produced "+product.list.size()); notify(); } } } public producer(product product) { this.product = product; } } class consumer implements runnable{ product product; @override public void run() { // todo auto-generated method stub while(true){ synchronized (this) { notify(); while(product.list.size() == 0){ seek { system.out.println("going wait..."+ product.list.size()); wait(); } grab (interruptedexception e) { // todo auto-generated grab block e.printstacktrace(); } } system.out.println("consumed"+ product.consume()); } } } public consumer(product product) { this.product = product; } }

output it's giving:

going wait...0 produced 1 produced 2

as can see consumer not coming in action after wait() call.

please help!

your producer , consumer each synchronizing, waiting , notifying their own monitor. need give them shared monitor utilize synchronization etc.

for example:

object monitor = new object(); product pro = new product(); producer produce = new producer(monitor, pro); consumer consume = new consumer(monitor, pro);

change both producer , consumer constructors take parameter (of type object) , save in field, alter synchronized(this) synchronized(monitor), wait() monitor.wait() , notify() monitor.notify() , well.

(you could utilize product synchronize on, prefer utilize object only used synchronization, or object of thread-centric class designed this.)

also, note code feels un-java-like due class names, should product, producer , consumer follow normal java naming conventions.

java multithreading

No comments:

Post a Comment