持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第21天,点击查看活动详情
线程池使用方法awaitTermination(long timeout,TimeUnit unit)
方法awaitTermination(long timeout,TimeUnit unit)的作用是查看在指定的时间之间,线程池是否已经终止工作,就是最多等待多少时间后去判断线程池是否已经停止工作了。
线程执行代码如下:
public class FirstRunnable implements Runnable {
@Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() +" 开始时间:"+System.currentTimeMillis());
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName() +" 结束时间:"+System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行类代码如下:
public class AwaitTerminationRun {
public static void main(String[] args) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
FirstRunnable firstRunnable = new FirstRunnable();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 6, 999, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
threadPoolExecutor.execute(firstRunnable);
threadPoolExecutor.shutdown();
try {
System.out.println("主线程开始时间:"+simpleDateFormat.format(new Date()));
threadPoolExecutor.awaitTermination(10,TimeUnit.SECONDS);
System.out.println(threadPoolExecutor.isTerminated());
System.out.println("主线程结束时间:"+simpleDateFormat.format(new Date()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果如下:
pool-1-thread-1 开始时间:15:23:41
主线程开始时间:15:23:41
pool-1-thread-1 结束时间:15:23:42
true
主线程结束时间:15:23:42
从运行结果看出主线程输出时间是线程执行完毕后的时间,就是说方法awaitTermination()被执行时,如果池中有任务在被执行时,则调用awaitTermination()方法出现阻塞,等待指定的时间,如果没有任务时则不再阻塞。 修改运行类代码如下:
public class AwaitTerminationRun {
public static void main(String[] args) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
FirstRunnable firstRunnable = new FirstRunnable();
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 6, 999, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
for (int i = 0; i < 4; i++) {
threadPoolExecutor.execute(firstRunnable);
}
threadPoolExecutor.shutdown();
try { System.out.println(threadPoolExecutor.awaitTermination(Integer.MAX_VALUE,TimeUnit.SECONDS)+" 全部任务执行完毕时间:"+simpleDateFormat.format(new Date()));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行结果如下:
pool-1-thread-1 开始时间:17:02:32
pool-1-thread-2 开始时间:17:02:32
pool-1-thread-1 结束时间:17:02:33
pool-1-thread-2 结束时间:17:02:33
pool-1-thread-2 开始时间:17:02:33
pool-1-thread-1 开始时间:17:02:33
pool-1-thread-2 结束时间:17:02:34
pool-1-thread-1 结束时间:17:02:34
true 全部任务执行完毕时间:17:02:34
从运行结果看出方法awaitTermination()和shutdown() 结合时可以实现等待执行完毕的效果,因为使用awaitTermination()方法具有阻塞性,如果awaitTermination()方法正在阻塞的过程中任务执行完毕,则awaitTermination()取消阻塞继续执行后续的代码。