带队列的Java并发
我试图做的基本上是启动新线程,将它们添加到队列中,然后在它们退出队列时执行其余的代码。我不确定将它们添加到队列的最佳方式是什么,以及如何在某个点暂停线程并在它们退出队列时通知它们。我以前没有用Java做过太多并发编程。任何帮助或建议都将不胜感激!多亏了您可以使用,基本上是根据多个可自定义规则创建一个线程池 为了确保所有线程在处理剩余代码之前都完成了各自的工作,您只需调用带队列的Java并发,java,multithreading,concurrency,queue,Java,Multithreading,Concurrency,Queue,我试图做的基本上是启动新线程,将它们添加到队列中,然后在它们退出队列时执行其余的代码。我不确定将它们添加到队列的最佳方式是什么,以及如何在某个点暂停线程并在它们退出队列时通知它们。我以前没有用Java做过太多并发编程。任何帮助或建议都将不胜感激!多亏了您可以使用,基本上是根据多个可自定义规则创建一个线程池 为了确保所有线程在处理剩余代码之前都完成了各自的工作,您只需调用ThreadPoolExecutor的waittermination方法,然后调用最终的ThreadPoolExecutor的s
ThreadPoolExecutor
的waittermination
方法,然后调用最终的ThreadPoolExecutor
的shutdown
方法
您还可以在调用wait termination
后发送notify
/notifyAll
,以唤醒其他一些依赖结果的线程
在中编写了一个示例(由ThreadPoolExecutor
实现) wait()
和notify()
可用于此操作,例如:
class QueuedThread extends Thread {
private volatile boolean wait = true; //volatile because otherwise the thread running run() might cache this value and run into an endless loop.
public void deQueue() {
synchronized(this) {
wait = false;
this.notify();
}
}
public void run() {
synchronized(this) {
while (wait) { //You need this extra mechanism because wait() can come out randomly, so it's a safe-guard against that (so you NEED to have called deQueue() to continue executing).
this.wait();
}
}
//REST OF RUN METHOD HERE
}
}
只要在应该取消排队时调用
queuedThread.deQueue()
。为什么要在等待时同步?这是非常错误的。你不应该在一个会change@JohnVint我通常使用特定的锁,但我认为应该简化。你说得对,固定密码。