public class ThreadPoolDemo {
private static ExecutorService pool = Executors.newFixedThreadPool(50);
private static CountDownLatch latch = new CountDownLatch(2);
public static void main(String[] args) {
pool.submit(() -> {
// 启用一个线程进行任务分发,分发任务给线程池
for (int i = 0; i < 10; i++) {
int finalI = i;
pool.submit(() -> {
System.out.println("A:" + finalI);
});
}
// 任务分发完成,计数器减1
latch.countDown();
});
pool.submit(() -> {
// 启用一个线程进行任务分发,分发任务给线程池
for (int i = 0; i < 20; i++) {
int finalI = i;
pool.submit(() -> {
System.out.println("B:" + finalI);
});
}
// 任务分发完成,计数器减1
latch.countDown();
});
try {
// 等待所有任务都分发给线程池
latch.await();
// 关闭线程池,线程池等待池内所有线程执行完
pool.shutdown();
// 等待线程池成功关闭(所有线程都执行完了),最久等待一天
pool.awaitTermination(1L, TimeUnit.DAYS);
System.out.println("所有任务都完成了!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Java线程池的简单运用
最新推荐文章于 2024-05-25 12:01:51 发布