如何在 java 中将参数传递给已经运行的线程——而不是在构造函数中,并且可能不使用 wait()(可能??)
类似于 How can I pass a parameter to a Java Thread? 中的评论
Do you mean passing a parameter to an already running thread ? Because all the current answers are about passing parameters to new threads... – Valentin Rocher May 18 '09 at 10:43
[编辑]
是的,我一直在寻找类似于生产者/消费者模式的东西。
我想要一个类似线程的东西,其中有处理并准备就绪 用于键盘输入。另一个线程只是监视网络并通过 将接收到的文本发送给处理线程。
最佳答案
也许你真正需要的是阻塞队列。当你创建线程时,你将阻塞队列传入,线程应该不断检查队列中是否有任何元素。在线程之外,您可以在线程“运行”时将元素放入队列。阻塞队列可以防止线程在无事可做时退出。
public class Test {
public static void main(String... args) {
final BlockingQueue<String> queue = new LinkedBlockingQueue<String>();
Thread running = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
String data = queue.take();
//handle the data
} catch (InterruptedException e) {
System.err.println("Error occurred:" + e);
}
}
}
});
running.start();
// Send data to the running thread
for (int i = 0; i < 10; i++) {
queue.offer("data " + i);
}
}
}
关于java - 如何将参数传递给java中已经运行的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12049369/