2 回答
TA贡献1809条经验 获得超8个赞
正如评论所提到的,最简单的方法是在 3 个线程中的每一个上调用 join() :thread1.join(); thread2.join(); thread3.join();
或者使用 aCountDownLatch
虽然它涉及更多(但在概念上可能更“正确”):
latch = new CountDownLatch(3)
在完成任务
latch.countDown()
后让每个线程去做。让主线程
latch.await()
- 瞧。
TA贡献1887条经验 获得超5个赞
与其手动创建Threads ,不如使用ExecutorService API. 使用ExecutorService您可以提交长时间运行的操作,结果您将收到Future实例,让您等到操作完成。
请参阅下面的示例,该示例显示了该想法:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class Threads {
public static void main(String[] args) {
new Threads().myMethod();
}
private String myMethod() {
ExecutorService executor = Executors.newFixedThreadPool(3);
List<Future<?>> futures = new ArrayList<>(3);
futures.add(executor.submit(this::LongRunningOperation1));
futures.add(executor.submit(this::LongRunningOperation2));
futures.add(executor.submit(this::LongRunningOperation3));
for (Future<?> future : futures) {
try {
future.get();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("All operations are finished!");
return "Done";
}
private void LongRunningOperation1() {
sleep(TimeUnit.SECONDS.toMillis(1));
System.out.println("LongRunningOperation1 is finished!");
}
private void LongRunningOperation2() {
sleep(TimeUnit.SECONDS.toMillis(2));
System.out.println("LongRunningOperation2 is finished!");
}
private void LongRunningOperation3() {
sleep(TimeUnit.SECONDS.toMillis(3));
System.out.println("LongRunningOperation3 is finished!");
}
private void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
上面的代码打印:
LongRunningOperation1 is finished!
LongRunningOperation2 is finished!
LongRunningOperation3 is finished!
All operations are finished!
添加回答
举报