gpt4 book ai didi

java - 如何在Java线程中监听特定时间?

转载 作者:行者123 更新时间:2023-12-02 02:04:43 25 4
gpt4 key购买 nike

我正在创建多个线程,并且希望每个线程在其 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com