java - why consumer thread is starting first? -
package producerconsumer; public class queue { int item; boolean isempty=false; public int put(int item) { this.item=item; return this.item; } public int get() { return item; } } package producerconsumer; public class producer extends thread{ queue q; public producer(queue q) { this.q=q; } @override public void run() { synchronized (q) { for(int i=1;i<=5;i++) { if(q.isempty==false) try { q.wait(); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } system.out.println("producer produced = "+q.put(i)); q.isempty=false; q.notify(); try { thread.sleep(2000); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } } } } }
package producerconsumer;
public class consumer extends thread { queue q; public consumer(queue q) { this.q=q; } @override public void run() { // todo auto-generated method stub synchronized (q) { for(int i=1;i<=5;i++) { if(q.isempty==true) try { q.wait(); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } system.out.println("item consumed:"+q.get()); q.isempty=true; q.notify(); } } } }
package producerconsumer;
public class mainapp { public static void main(string[] args) { queue q=new queue(); thread t1=new thread(new producer(q)); //t1.setpriority(1); t1.start(); thread t2=new thread(new consumer(q)); t2.start(); } }
this output:
item consumed:0 producer produced = 1 item consumed:1 producer produced = 2 item consumed:2 producer produced = 3 item consumed:3 producer produced = 4 item consumed:4 producer produced = 5
question is: why consumer thread running first ? tried setting priority producer thread also. not working. also, if there other flaw in code or design flaw in code, please mention.
synchronized (q) {
you told of threads never run @ same time.
defeats purpose of threads.
Comments
Post a Comment