だから私はプロデューサーの消費者の問題をシミュレートしました。以下のコードがあります。私の質問はこれです: 彼が一定の while(true) にいる場合、消費者はどのように停止しますか。
以下のコードでは、追加しました
if (queue.peek()==null)
Thread.currentThread().interrupt();
この例ではうまく機能します。しかし、私の現実世界の設計では、これは機能しません (プロデューサーがデータを「プット」するのに時間がかかることがあるため、コンシューマーでスローされた例外は正しくありません。一般に、「毒」データを入れることができることはわかっています)。 Object is XYZ and I can check it in consumer. しかし、この毒はコードの見栄えを悪くします. 誰かが別のアプローチを持っているのだろうか.
public class ConsumerThread implements Runnable
{
private BlockingQueue<Integer> queue;
private String name;
private boolean isFirstTimeConsuming = true;
public ConsumerThread(String name, BlockingQueue<Integer> 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 ------->"+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();
}
}
}