Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带队列的Java并发_Java_Multithreading_Concurrency_Queue - Fatal编程技术网

带队列的Java并发

带队列的Java并发,java,multithreading,concurrency,queue,Java,Multithreading,Concurrency,Queue,我试图做的基本上是启动新线程,将它们添加到队列中,然后在它们退出队列时执行其余的代码。我不确定将它们添加到队列的最佳方式是什么,以及如何在某个点暂停线程并在它们退出队列时通知它们。我以前没有用Java做过太多并发编程。任何帮助或建议都将不胜感激!多亏了您可以使用,基本上是根据多个可自定义规则创建一个线程池 为了确保所有线程在处理剩余代码之前都完成了各自的工作,您只需调用ThreadPoolExecutor的waittermination方法,然后调用最终的ThreadPoolExecutor的s

我试图做的基本上是启动新线程,将它们添加到队列中,然后在它们退出队列时执行其余的代码。我不确定将它们添加到队列的最佳方式是什么,以及如何在某个点暂停线程并在它们退出队列时通知它们。我以前没有用Java做过太多并发编程。任何帮助或建议都将不胜感激!多亏了您可以使用,基本上是根据多个可自定义规则创建一个线程池

为了确保所有线程在处理剩余代码之前都完成了各自的工作,您只需调用
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我通常使用特定的锁,但我认为应该简化。你说得对,固定密码。