ThreadPoolTaskExecutor学习

2019-10-12 08:33:03来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

ThreadPoolTaskExecutor学习

1. ThreadPoolTaskExecutor学习

1.1. 前言

  • 我们知道一般创建线程池,我们都用ThreadPoolExecutor,但实际上Spring它也对该线程池做了一层封装,他就是ThreadPoolTaskExecutor

1.2. 代码例子

  • 它的创建方式也很简单,各个属性直接通过set设置属性值,最后调用initialize()方法初始化,实际去做的就是初始化ThreadPoolExecutor
  • 它封装了回调监听方法ListenableFutureCallback,可以用作异步回调处理
/**
 * @author laoliangliang
 * @date 2019/10/10 10:10
 */
public class ExecutorDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(1);
        executor.setMaxPoolSize(5);
        executor.setQueueCapacity(1);
        executor.setBeanName("mybean");
        executor.setThreadNamePrefix("mytask-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.initialize();

        List<FutureTask<String>> result = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            FutureTask<String> futureTask = new FutureTask<>(() -> {
                System.out.println("hello world!");
                Thread.sleep(200);
                return "hello "+Thread.currentThread().getName();
            });
            executor.submit(futureTask);
            result.add(futureTask);
        }
        for (FutureTask<String> futureTask : result) {
            try {
                System.out.println(futureTask.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        }

        ListenableFuture<?> runnable = executor.submitListenable(() -> {
            Thread.sleep(1000);
            System.out.println("runnable");
            return "runnable result";
        });
        runnable.addCallback(new ListenableFutureCallback<Object>() {
            @Override
            public void onFailure(Throwable e) {
              e.printStackTrace();
            }

            @Override
            public void onSuccess(Object o) {
                System.out.println("success "+o.toString());
            }
        });

        System.out.println(runnable.get());
        executor.shutdown();
    }
}

结果

[INFO] ThreadPoolTaskExecutor - -Initializing ExecutorService  'mybean'
hello world!
hello world!
hello world!
hello world!
hello mytask-1
hello world!
hello mytask-1
hello mytask-2
hello mytask-3
hello mytask-4
runnable
runnable result
[INFO] ThreadPoolTaskExecutor - -Shutting down ExecutorService 'mybean'
success runnable result

1.3. 总结

  • 当使用线程池时,可以考虑直接使用spring封装的线程池,前一篇@Async注解实现的线程池就是用的它,我觉得这个可能更加直观且功能丰富,特别当你需要异步处理事件的时候

原文链接:https://www.cnblogs.com/sky-chen/p/11654903.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:SpringBootSecurity学习(19)前后端分离版之OAuth2.0 token的存

下一篇:SpringCache - 请求级别缓存的简易实现