先看下线程池最基本的用法示例;
1、ThreadPoolExecutor
使用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 10sfinal 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 3sfinal 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 7sfinal 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