Java BlockingQueue take()与轮询(时间,单位)
我认为有些人错误地比较了take和poll,但我发现比较take和polltime是合理的,因为这两个单位都是BlockingQueue提供的,并且都是blocking告诉队列不是空的,在case或poll或超时的情况下,好吧,让我们开始比较,通常我使用take作为BlockingQueue,但我面临以下问题: 在循环内处理中断。 等待被外界打断。 如何使用Kill-Bill或interrupt-thread停止队列上的循环 特别是在使用Java 8 streams时,我知道我需要停止从队列中检索数据,并以更好的方式关闭它,所以我想让等待一段时间之后,我可以停止检索数据,然后我找到polltime,unit,它将适合此想法检查代码如下:Java BlockingQueue take()与轮询(时间,单位),java,multithreading,queue,blockingqueue,Java,Multithreading,Queue,Blockingqueue,我认为有些人错误地比较了take和poll,但我发现比较take和polltime是合理的,因为这两个单位都是BlockingQueue提供的,并且都是blocking告诉队列不是空的,在case或poll或超时的情况下,好吧,让我们开始比较,通常我使用take作为BlockingQueue,但我面临以下问题: 在循环内处理中断。 等待被外界打断。 如何使用Kill-Bill或interrupt-thread停止队列上的循环 特别是在使用Java 8 streams时,我知道我需要停止从队列中检
public static void main(String[] args) throws InterruptedException {
BlockingQueue<Integer> q = new LinkedBlockingQueue<Integer>();
ExecutorService executor = Executors.newCachedThreadPool();
executor.submit(() -> {
IntStream.range(0, 1000).boxed().forEach(i -> {
try {
q.put(i);
} catch (InterruptedException e) {
currentThread().interrupt();
throw new RuntimeException(e);
}
});
});
....
// Take
Future fTake = executor.submit(() -> {
try {
while (!Thread.currentThread().isInterrupted()) {
System.out.println(q.take());
}
} catch (InterruptedException e) {
currentThread().interrupt();
throw new RuntimeException(e);
}
});
//to stop it I have to do below code "Expecting that execution will take 1 sec"
executor.shutdown();
sleep(1000);
fTake.cancel(true);
....
// poll there is no need to expect time till processing will be done
Future fPoll = executor.submit(() -> {
try {
Integer i;
while ((i = q.poll(100, TimeUnit.MILLISECONDS)) != null)
System.out.println(i);
} catch (InterruptedException e) {
currentThread().interrupt();
throw new RuntimeException(e);
}
});
executor.shutdown();
}
我认为轮询代码更干净,不需要依赖于中断,也不需要估计执行时间或使代码决定何时中断线程,您认为呢
注1:我确信第二种解决方案也有缺点,比如直到超时才获取数据,但我认为您将知道什么是适合您的案例的超时
注2:如果用例需要永远等待,而生产者是低频率提供数据的,我认为采取解决方案更好。看起来这里可能有几个不同的问题。。。或者没有。很难说出你在问什么。你的民意调查示例看起来像是一种聪明的把戏,它让代码通过QA测试,然后在重要的演示或客户站点失败。这取决于制作人在不将另一个项目推到队列中的情况下,决不能让超过1/10秒的时间过去。在现实世界中,谁知道什么会让制作人犹豫不决?然后消费者会过早退出。