所以我模拟了我的生产者消费者问题,我有下面的代码。我的问题是这样的:如果消费者在不断的 while(true) 中,他如何停止。
在下面的代码中,我添加了
if (queue.peek()==null)
Thread.currentThread().interrupt();
在这个例子中效果很好。但在我的现实世界设计中,这是行不通的(有时生产者需要更长的时间来“放置”数据,因此消费者抛出的异常是不正确的。一般来说,我知道我可以放置“毒药”数据比如 Object 是 XYZ ,我可以在消费者中检查它。但是这种毒药让代码看起来很糟糕。想知道是否有人有不同的方法。
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();
}
}
}