Executor框架(四)ThreadPoolTaskExecutor和ThreadPoolExecutor区别

ThreadPoolTaskExecutorThreadPoolExecutor两个类都是作为线程池的作用,最本质的区别来自于:ThreadPoolExecutor是在java.util.concurrent包下;ThreadPoolTaskExecutor是在org.springframework.scheduling.concurrent包下。

分析两个类的继承关系

ThreadPoolTaskExecutor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class ThreadPoolTaskExecutor extends ExecutorConfigurationSupport 
implements AsyncListenableTaskExecutor, SchedulingTaskExecutor {

@Nullable
private ThreadPoolExecutor threadPoolExecutor;

//...
}

public abstract class ExecutorConfigurationSupport extends CustomizableThreadFactory implements BeanNameAware, InitializingBean, DisposableBean {
//...
}

public interface AsyncListenableTaskExecutor extends AsyncTaskExecutor {
//...
}

public interface SchedulingTaskExecutor extends AsyncTaskExecutor {
//...
}

ThreadPoolExecutor

1
2
3
4
5
6
7
8
9
10
11
12
public class ThreadPoolExecutor extends AbstractExecutorService { 
//...
}

public abstract class AbstractExecutorService implements ExecutorService {
//...
}


public interface ExecutorService extends Executor {
//...
}

从上继承关系可知:
ThreadPoolExecutor是一个java类,不提供spring生命周期和参数装配。
ThreadPoolTaskExecutor实现了InitializingBean, DisposableBean ,xxaware等,具有spring特性。
AsyncListenableTaskExecutor提供了监听任务方法(相当于添加一个任务监听,提交任务完成都会回调该方法)。

简单理解:

  1. ThreadPoolTaskExecutor内部封装了ThreadPoolExecutor并进行了增强,扩展了更多特性。
  2. ThreadPoolTaskExecutor只关注自己增强的部分,任务执行还是ThreadPoolExecutor处理。
  3. 前者spring自己用着爽,后者离开spring我们用ThreadPoolExecutor爽。

注意:ThreadPoolTaskExecutor 不会自动创建ThreadPoolExecutor需要手动调initialize()方法才会创建; 如果使用@Bean注解注入就不需手动,会自动调用InitializingBeanafterPropertiesSet()方法来调initialize()

------ 本文完 ------