简体   繁体   English

Java - 在所有线程完成后等待初始化活动

[英]Java - waiting to initialize an activity after all threads are completed

I have few threads that performs an actvity in parallel.我有几个并行执行活动的线程。 I would have to proceed with the subsequent actvity only after all the threads are completed.只有在所有线程完成后,我才必须继续进行后续活动。 Is there a way to achieve this?有没有办法做到这一点?

You should take a look at the join() method in the Thread class .您应该查看Thread class 中的join()方法 A join can be used to allow one thread to wait for another to complete.连接可用于允许一个线程等待另一个线程完成。 It's also overloaded to allow for the specification of a time to wait for the other thread to finish.它还超载以允许指定等待其他线程完成的时间。 Joins are discussed as part of the Java Tutorial on Concurrency . 联接作为 Java 并发教程的一部分进行了讨论

for all threads do thread.join().对所有线程执行 thread.join()。

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join () http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join ()

You can use Thread.join() in order to cause a wait until thread completion.您可以使用 Thread.join() 来等待线程完成。 Take a look at the Javadoc for more information.查看 Javadoc 以获取更多信息。

I think using a http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CountDownLatch.html is actually preferable over Thread.join() as it should scale better.我认为使用http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CountDownLatch.html实际上比 Thread.join() 更好,因为它应该更好地扩展。

Conceptually, a way to address your problem is to create an observer object which will be referenced by every threads you are running.从概念上讲,解决您的问题的一种方法是创建一个观察者 object ,您正在运行的每个线程都会引用它。 Once a thread is done it notifies the observer that it performed his task.一旦线程完成,它就会通知观察者它执行了他的任务。 Each time the Observer receive this kind of notification, it increment a counter, once the counter reach the number of threads, this means that all the threads are completed.每次观察者收到这种通知,它都会增加一个计数器,一旦计数器达到线程数,这意味着所有线程都完成了。 then the Observer can start the final task.然后观察者可以开始最后的任务。

That is for the theory.那是为了理论。 If you want there is a built-in java class for that: CountDownLatch如果你想要,有一个内置的 java class: CountDownLatch

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

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