作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在创建多个线程,并且希望每个线程在其 BlockingQueue 中监听任何新消息 2 秒,然后消失。我正在使用以下代码:
public class Main {
public static void main(String[] argv) throws Exception {
int capacity = 10;
BlockingQueue<String> queue = new ArrayBlockingQueue<String>(capacity);
ArrayList<String> names = new ArrayList<String>();
names.add("Apple"); names.add("Banana"); names.add("Mango");
HashMap<String, Worker> workermap = new HashMap<String, Worker>();
for (String name: names) {
Worker a_worker = new Worker(queue);
a_worker.setName(name);
a_worker.start();
workermap.put(name, new Worker(queue));
}
queue.put("Hello ");
}
}
class Worker extends Thread {
BlockingQueue<String> q;
Worker(BlockingQueue<String> q) {
this.q = q;
}
public void run() {
try {
long start = System.currentTimeMillis();
long end = start + 2*1000;
while (true) {
String x = q.take();
if(System.currentTimeMillis()>=end){
System.out.println("No new message since two seconds, killing thread " + this.getName());
Thread.interrupted();
// break;
}
// if (x == null) {
// break;
// }
System.out.println(x + "from " + this.getName());
}
} catch (InterruptedException e) {
}
}
}
我希望输出如下:
Hello from Apple
Hello from Banana
Hello from Mango
No new message since two seconds, killing thread Apple
No new message since two seconds, killing thread Banana
No new message since two seconds, killing thread Mango
但我只是收到了来自 Apple 的问候
,之后就什么也没有了。该过程继续进行,没有任何进一步的输出。除了使用计时器杀死线程之外,我还尝试检查队列元素是否为空,但没有成功。我哪里出错了?
最佳答案
正如已经提到的,你需要使用 pool 而不是 take() ,你也不能使用 Thread.interrupted();
至interrupt
一个thread
。您需要使用Thread.currentThread().interrupt();
。另外,您不需要将时间检查为 BlockingQueue#poll
会等待2
秒。
while (!Thread.currentThread().isInterrupted()) {
String x = q.poll(2, TimeUnit.SECONDS);
if (x == null)
System.out.println("No new message since two seconds, killing thread " + this.getName());
Thread.currentThread().interrupt();
System.out.println(x + "from " + this.getName());
}
输出:
No new message since two seconds, killing thread Mango
Hello from Mango
No new message since two seconds, killing thread Apple
nullfrom Apple
No new message since two seconds, killing thread Banana
nullfrom Banana
编辑:但是我相信你根本不需要循环。只需下面的代码就可以很好地为您工作。
public void run() {
try {
String x = q.poll(2, TimeUnit.SECONDS);
if (x == null)
System.out.println("No new message since two seconds, killing thread " + this.getName());
System.out.println(x + "from " + this.getName());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
关于java - 如何在Java线程中监听特定时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50990795/
我是一名优秀的程序员,十分优秀!