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
注解实现的线程池就是用的它,我觉得这个可能更加直观且功能丰富,特别当你需要异步处理事件的时候
如果,您希望更容易地发现我的新博客,不妨点击一下【关注我】。
我的写作热情也离不开您的肯定支持,感谢您的阅读,我是【老梁】!