ThreadPoolExecutor
,但实际上Spring它也对该线程池作了一层封装,他就是ThreadPoolTaskExecutor
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(); } }
结果spring
[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
@Async
注解实现的线程池就是用的它,我以为这个可能更加直观且功能丰富,特别当你须要异步处理事件的时候