Note that there are some explanatory texts on larger screens.

plurals
  1. POproducer - consume; how does the consumer stop?
    primarykey
    data
    text
    <p>So I have simulated my producer consumer problem and I have the code below. My question is this: how does the consumer stops if he's in constant while(true).</p> <p>In the code below, I've added</p> <pre><code> if (queue.peek()==null) Thread.currentThread().interrupt(); </code></pre> <p>which works nicely in this example. But in my real world design, this doesn't work (sometimes it takes longer time to the producer to 'put' the data so the exception thrown in the consumer is incorrect. In general, I know I can put a 'poison' data such as Object is XYZ and I can check it in the consumer. But this poison makes the code really look bad. Wonder if anyone has a different approach.</p> <pre><code>public class ConsumerThread implements Runnable { private BlockingQueue&lt;Integer&gt; queue; private String name; private boolean isFirstTimeConsuming = true; public ConsumerThread(String name, BlockingQueue&lt;Integer&gt; queue) { this.queue=queue; this.name=name; } @Override public void run() { try { while (true) { if (isFirstTimeConsuming) { System.out.println(name+" is initilizing..."); Thread.sleep(4000); isFirstTimeConsuming=false; } try{ if (queue.peek()==null) Thread.currentThread().interrupt(); Integer data = queue.take(); System.out.println(name+" consumed -------&gt;"+data); Thread.sleep(70); }catch(InterruptedException ie) { System.out.println("InterruptedException!!!!"); break; } } System.out.println("Comsumer " + this.name + " finished its job; terminating."); }catch (InterruptedException e) { e.printStackTrace(); } } </code></pre> <p>}</p>
    singulars
    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.
    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