先看下线程池最基本的用法示例;
使用ThreadPoolExecutor 定义一个线程池:
/**
* 线程池
*/
private static final ExecutorService executorService = new ThreadPoolExecutor(3, 10, 60, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(100),
r -> {
Thread thread = new Thread(r);
thread.setName("myThreadPoolExecutor");
//设置异常捕获器
thread.setUncaughtExceptionHandler((t, e) -> log.error("[message]async exec task error! e:{}", e.getMessage()));
return thread;
}, new ThreadPoolExecutor.AbortPolicy());
接下来分别依次提交3个任务A/B/C,任务类型为有返回值的Callable task,每个任务的执行时间不同;异步任务提交的结果为Future类型,提交后接下来按序对每个Future对象调用future.get方法获取其结果,代码如下:
/**
* 测试ExecutorService获取异步结果的顺序及实际执行时间
*/
private static void testThreadPool() {
List<Future<String>> futureList = Lists.newArrayList();
// 记录A/B/C的任务完成时间
List<AtomicLong> taskFinshTimeList = Lists.newArrayList();
AtomicLong finishA = new AtomicLong();
AtomicLong finishB = new AtomicLong();
AtomicLong finishC = new AtomicLong();
// A cost 10s
final Future<String> futureA = executorService.submit(() -> {
log.warn("exec A start");
final long start = System.currentTimeMillis();
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
log.error("A InterruptedException occur!");
}
finishA.set(System.currentTimeMillis());
taskFinshTimeList.add(finishA);
log.warn("exec A finish cost=[{}]ms", finishA.get() - start);
return "A";
});
futureList.add(futureA);
// B cost 3s
final Future<String> futureB = executorService.submit(() -> {
log.warn("exec B start");
final long start = System.currentTimeMillis();
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
log.error("B InterruptedException occur!");
}
finishB.set(System.currentTimeMillis());
taskFinshTimeList.add(finishB);
log.warn("exec B finish cost=[{}]ms", finishB.get() - start);
return "B";
});
futureList.add(futureB);
// C cost 7s
final Future<String> futureC = executorService.submit(() -> {
log.warn("exec C start");
final long start = System.currentTimeMillis();
try {
TimeUnit.SECONDS.sleep(7);
} catch (InterruptedException e) {
log.error("C InterruptedException occur!");
}
finishC