您可以为此使用CountDownLatch。 CountDownLatch 是
一种同步辅助工具,允许一个或多个线程等待,直到在其他线程中执行的一组操作完成。
CountDownLatch countDownLatch = new CountDownLatch(REPEAT);
for (int i = 0; i < REPEAT; i++) {
new Thread(new MyTask(i, countDownLatch)).start();
Thread.sleep(1);
}
finalTask(countDownLatch);
我创建了一个 CountDownLatch,其 count 被初始化为 REPEAT 的值。我将它传递给每个线程和finalTask 方法。
每个线程在完成工作后都应该调用 countDownLatch 的countDown 方法。
private static class MyTask implements Runnable {
private int i;
private CountDownLatch countDownLatch;
private MyTask(int i, CountDownLatch countDownLatch) {
this.i = i;
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
//Perform some task
System.out.println("Running " + i);
countDownLatch.countDown();
}
}
finalTask 方法的第一行应该调用 CountDownLatch 的await 方法。这将导致运行finalTask 的线程等待,直到 CountDownLatch 的计数达到 0,即,直到所有线程(它们的 REPEAT 数量)都完成并调用 CountDownLatch 的countDown。
private static void finalTask(CountDownLatch countDownLatch) {
try {
countDownLatch.await(); //this will wait until the count becomes 0.
} catch (InterruptedException e) {
e.printStackTrace(); //handle it appropriately
}
//Some code to be executed once all threads stopped running
System.out.println("All done");
}