Note that there are some explanatory texts on larger screens.

plurals
  1. POProducer Consumer thread management in java
    primarykey
    data
    text
    <p>I am implementing basic producer consumer problem in java but my code is getting hanged and consumer is not consuming when producer fills the buffer. below is the code</p> <pre><code>import java.util.Vector; class hi{ static int i; } class Producer implements Runnable { volatile Vector&lt;Integer&gt;queue; Producer(Vector&lt;Integer&gt; q) { queue=q; } public void run() { while(true) { try{ produce(); } catch(Exception e) { } } } public synchronized void produce() throws InterruptedException { while(queue.size()==5) { synchronized(queue) { queue.wait(); } } int t=hi.i++; Thread.sleep(2000); System.out.println("adding "+t); queue.add(t); queue.notify(); } } class Consumer implements Runnable { volatile Vector&lt;Integer&gt;queue; Consumer(Vector&lt;Integer&gt; q) { queue=q; } public void run() { while(true) { System.out.println("kaka"); try{ consume(); } catch(Exception e) { } } } public synchronized void consume() throws InterruptedException { //Thread.sleep(2000); while(queue.size()==0) { synchronized(queue) { queue.wait(); } } System.out.println("Removing "+queue.get(0)); queue.remove(0); queue.notify(); } } public class ProducerConsumer { public static void main(String [] args) throws InterruptedException { Vector&lt;Integer&gt;q=new Vector&lt;Integer&gt;(); Producer p=new Producer(q); Thread p1=new Thread(p); Consumer c=new Consumer(q); Thread c1=new Thread(c); p1.start(); Thread.sleep(2000); System.out.println("kailash"); c1.start(); } } </code></pre> <p>Above I commented Thread.sleep(2000) in consume method.If I uncomment this the code works perfectly fine.Kindly help me in understanding the issue.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload