JAVA多线程问题 — 如何正确使用异步线程和线程执行器?

发布时间:2024年01月19日

先看下线程池最基本的用法示例;

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 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
文章来源:https://blog.csdn.net/qq_38658567/article/details/135693010
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。