所以我模拟了我的生产者消费者问题,我有下面的代码。我的问题是这样的:如果消费者在(真实)时间内保持不变,消费者会如何停下来。生产者 - 消费;消费者如何停止?
在下面的代码,我已经添加
if (queue.peek()==null)
Thread.currentThread().interrupt();
在这个例子很好地工作。但在我的真实世界设计中,这不起作用(有时,生产者需要更长时间才能“放入”数据,因此在消费者中抛出的异常是不正确的。一般来说,我知道我可以将“毒性”数据如对象是某某,我可以在消费者进行检查。但这种毒药使得代码真的看不好。不知道是否有人有不同的方法。
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();
}
}
}
是的,这被称为'毒'它工作正常,我只是想知道是否有更好的方法。 – adhg 2012-04-27 15:59:14
@adhg - 所以我的答案是:这似乎是唯一可行的简单技术。对我而言,它似乎也是'干净的'(尽管什么是'干净'实际上是个人意见的问题)。 – ArjunShankar 2012-04-27 16:15:31
我完全同意你的看法。我最终使用这个解决方案。感谢+1 – adhg 2012-04-28 01:55:10