[英]Java: Wait/Notify on multiple threads
I have a class which holds a collection of references to workers threads that receive objects via TCP (1 per client). 我有一个类,其中包含对通过TCP(每个客户端1个)接收对象的工作线程的引用的集合。
I'm trying to make a method getMessage()
in my class which waits until any of the workers threads got a message and returns it. 我正在尝试在类中创建方法
getMessage()
,该方法要等到任何工作线程都收到一条消息并返回它。
What I got right now is a polling-system: 我现在得到的是一个轮询系统:
public Object getMessage() {
while (true) {
for (Worker w : workers.values())
if (w.msgNumber() != 0)
return w.getLastMsg();
Thread.sleep(100);
}
}
It works, but I don't think it's very scalable. 它可以工作,但是我认为它不是非常可扩展的。
I know I can do a wait(timeout)
on each worker, but the problem stays the same. 我知道我可以对每个工作人员执行
wait(timeout)
操作,但是问题仍然存在。
Is there some kind of wait/notify mechanism which waits for multiple threads? 是否存在某种等待多个线程的等待/通知机制?
You could look at using a blocking queue for communications between threads. 您可以考虑使用阻塞队列在线程之间进行通信。 The worker thread would insert into the queue, while the
getMessage()
function pulls a message from the queue. 工作线程将插入队列,而
getMessage()
函数从队列中提取一条消息。
How about something like: 怎么样:
try {
ServerSocket srv = new ServerSocket(port);
// Wait for connection from client.
while (true) {
System.out.println("Listening...");
// Waits for connection
new Thread(new ServerWorkerThread(srv.accept())).start();
}
} catch (IOException e) {
//handle
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.