81,091
社区成员
发帖
与我相关
我的任务
分享
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestCountDownLatch {
public static void main(String[] args) throws Exception {
// ExecutorService threadPool = Executors.newFixedThreadPool(5);
ExecutorService threadPool = Executors.newCachedThreadPool();
int[] ids = new int[150];
for(int i=0; i<ids.length; i++) {
ids[i] = i + 1;
}
CountDownLatch latch = new CountDownLatch(ids.length);
for(int i=0; i<ids.length; i++) {
threadPool.execute(new Task(ids[i], latch));
}
latch.await();
System.out.println("所有线程都执行完了");
threadPool.shutdown();
}
static class Task implements Runnable {
long id = 0;
CountDownLatch latch;
public Task(long id, CountDownLatch latch) {
this.id = id;
this.latch = latch;
}
public void run() {
try {
System.out.println("task" + id + " by " + Thread.currentThread().getId());
Thread.sleep(500);
} catch (Exception e) {
} finally {
latch.countDown();
}
}
}
}