简体   繁体   English

主线程等待其他线程

[英]Main thread wait for other threads

After seaching a lot and not finding a concrete answer 搜寻了很多之后并没有找到具体的答案

If I have two threads started: 如果我有两个线程启动:

Thread t1 = new Thread();
Thread t2 = new Thread();

t1.start();
t2.start();

After starting the threads I need the main thread to wait for these two thread to finish before printing the final result 启动线程后,我需要主线程等待这两个线程完成后才能打印最终结果

How can I make the main thread wait for both t1 and t2? 如何使主线程同时等待t1和t2?

A plain wait() would be enough? 一个简单的wait()就足够了吗?

Add

t1.join();
t2.join();

in your thread which should wait till t1 and t2 will finish their tasks (in your case call it from your main thread). 在您的线程中等待t1t2完成任务(在您的情况下,从主线程调用它)。

The answer depends... 答案取决于...

You could 你可以

Use a CountDownLatch which is probably the simplest solution. 使用CountDownLatch可能是最简单的解决方案。

This way you would simply wait on the latch until it has been signaled the prescribed number of times (by each Thread terminating). 这样,您只需在闩锁上wait ,直到已通过指定次数(通过每个Thread终止)发出信号为止。 This scales quite nicely as you increase the number of threads... 当您增加线程数时,这可以很好地扩展...

You could 你可以

Use join , but it would become tedious as you add more threads 使用join ,但是随着您添加更多线程,它将变得乏味

You could 你可以

Add each Thread to a List , loop through the list, removing those threads that are no longer alive and keep looping until the List is empty, but that's a rather heavy handed approach. 将每个Thread添加到List ,遍历该列表,删除不再活动的那些线程,并一直循环直到List为空,但这是一种繁重的做法。

You could 你可以

Combine the above solution with some kind of monitor lock which the loop would wait on and each Thread would notify when they complete, but it's not much cleaner and you could still end up waiting for non-existent threads... 将上面的解决方案与某种监视器锁结合在一起, loopwait该监视器锁,并且每个Thread在完成时都会notify ,但是这样做并不干净,您仍然可能最终等待不存在的线程...

You could 你可以

Use an ExecutorService and either use it's invokeAll and/or shutdown methods. 使用ExecutorService并使用它的invokeAll和/或shutdown方法。 See Executors for more details. 有关更多详细信息,请参见执行器 This also scales quite nicely and even has the added benefit of allowing you to use a Thread pool to better manage the system resourcs 这也可以很好地扩展,甚至具有允许您使用Thread池更好地管理系统资源的附加好处。

Check out the Thread#join method. 签出Thread#join方法。

Also, you might find using an ExecutorService (and friends) helpful. 此外,您可能会发现使用ExecutorService(和朋友)会有所帮助。 Its essentially thread pool/management and provides a lot of conveniences and IMO a cleaner API than threads. 它实质上是线程池/管理,并提供了许多便利,并且IMO提供了比线程更干净的API。 Barrier to entry is low... 进入门槛低...

You want Thread#join() . 您需要Thread#join() wait() is for signalling, join() is to wait for the thread to finish. wait()用于发出信号, join()用于等待线程完成。

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

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