方法一: threadPool.execute()
public static void main(String[] args) throws Exception {
// 初始化线程池, 参数一定要一定要一定要调好!!!!
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(20, 50,
4, TimeUnit.SECONDS, new ArrayBlockingQueue(10), new ThreadPoolExecutor.AbortPolicy());
// 记录单个任务的执行次数
int number = 10;
CountDownLatch countDownLatch = new CountDownLatch(number);
for (int i = 0; i < number; i++) {
int finalI = i;
threadPool.execute(new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程"+ finalI +"执行任务...");
// 任务个数 - 1, 直至为0时唤醒await()
countDownLatch.countDown();
}
}));
}
// 让当前线程处于阻塞状态,直到锁存器计数为零
countDownLatch.await();
// 关闭线程池
threadPool.shutdown();
System.out.println("线程全部执行完成");
}
方法二:threadPool.submit();
public static void main(String[] args) throws Exception { // 创建线程池 ThreadPoolExecutor threadPool = new ThreadPoolExecutor(10, 20, 0, TimeUnit.SECONDS, new LinkedBlockingDeque<>(1024)); // 记录单个任务的执行次数 final int number = 10; CountDownLatch countDownLatch = new CountDownLatch(number); for (int i = 0; i < number; i++) { int finalI = i; threadPool.submit(new Thread(new Runnable() { @Override public void run() { System.out.println("线程"+ finalI +"执行任务..."); // 任务个数 - 1, 直至为0时唤醒await() countDownLatch.countDown(); } })); } // 让当前线程处于阻塞状态,直到锁存器计数为零 countDownLatch.await(); // 关闭线程池 threadPool.shutdown(); // 打印结果 System.out.println("线程池任务执行完成!"); }