简体   繁体   English

Java线程池同步

[英]Java Thread Pool Synchronization

I would like to perform the following algorithm - this must be done in Java 我想执行以下算法 - 这必须在Java中完成

for(int i = 0; i< 100; i++){
    create 8 threads which perform a task
    wait for all threads to finish
}

It is desirable that threads are not continuously created and destroyed due to overheads (and the fact that each thread will have <20milli seconds of work), which brought about the idea of Thread Pools 1 . 由于开销(以及每个线程将具有<20毫秒的工作时间的事实),期望线程不被连续地创建和销毁,这带来了线程池1的想法。 I also know that using Executable 2 , one can call shutdown, and then awaitTermination. 我也知道使用Executable 2 ,可以调用shutdown,然后是awaitTermination。 However it is not desirable in this case due to the loop. 然而,在这种情况下由于环路是不可取的。 Thus how can thread synchronization occur? 那么如何进行线程同步呢?

I would like to synchronize threads in the thread pool as would be done using a traditional thread's join() method. 我想在线程池中同步线程,就像使用传统线程的join()方法一样。

Have you tried looking at a Cyclic Barrier . 你试过看过Cyclic Barrier吗? It is optimized to allow a group of threads to stop and wait till everyone has reached a common barrier. 它经过优化,允许一组线程停止并等待每个人都达到共同的障碍。 I can't seen any reason why it can't be used with known number of pooled threads with references to a common barrier. 我没有看到任何理由为什么它不能与已知数量的汇集线程一起使用,并引用了一个共同的障碍。 There could be some additional complexity if you need to synchronize on the callback invoked with the barriers await() count is reached because it executes in a different thread. 如果您需要在使用障碍await()计数调用的回调上进行同步,则可能会有一些额外的复杂性,因为它在不同的线程中执行。

You need to stick all your tasks in a queue, then feed the queue to a ThreadPoolExecutor . 您需要将所有任务都放在队列中,然后将队列提供给ThreadPoolExecutor You tell the thread pool executor how many threads to use and it takes care of executing the tasks. 您告诉线程池执行程序要使用多少个线程,它负责执行任务。

看看jdk 7的fork / join框架。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM