线程池——Executor、Executors、ExecutorService、ThreadPoolExecutor、ThreadPoolTaskExecutor之间的区别

java.util.concurrent.Executor 负责线程的使用和调度的根接口
|–ExecutorService 子接口: 线程池的主要接口
|–ThreadPoolExecutor 线程池的实现类
|–ScheduledExceutorService 子接口: 负责线程的调度
|–ScheduledThreadPoolExecutor : 继承ThreadPoolExecutor,实现了ScheduledExecutorService

 

线程池——Executor、Executors、ExecutorService、ThreadPoolExecutor、ThreadPoolTaskExecutor之间的区别_第1张图片

ExecutorService 接口继承了Executor 接口,是Executor 的子接口 

    1.Executor接口中定义了execute()方法,用来接收一个Runnable接口的对象,而ExecutorService接口中定义的submit()方法可以接收Runnable和Callable接口对象。

    2.Executor接口中execute()方法不返回任何结果,而ExecutorService接口中submit()方法可以通过一个 Future 对象返回运算结果。

    3.Executor和ExecutorService除了允许客户端提交一个任务,ExecutorService 还提供用来控制线程池的方法。
    比如:调用 shutDown() 方法终止线程池

Executors 类提供工厂方法用来创建不同类型的线程池

ThreadPoolExecutor

这个类是JDK中的线程池类,继承自Executor,里面有一个execute()方法,用来执行线程,线程池主要提供一个线程队列,队列中保存着所有等待状态的线程
线程池创建方式一:构造方法(传入相应的参数即可)

private static final ThreadPoolExecutor executor = 
new ThreadPoolExecutor(2, 2, 300, TimeUnit.SECONDS, 
new LinkedBlockingQueue(1200), 
new DiscardOldestPolicy());

线程池创建方式二:通过Executors工具类

ThreadPoolTaskExecutor

 这个类则是spring包下的,是sring为我们提供的线程池类

可以基于XML创建


 
    
    
        
        
        
        
        
        
        
        
        
        
    

基于配置类创建

@Configuration
public class TradeExecutorConfig {

    private static  final  String THREAD_NAME_PREFIX = "trade_executor_";

    private static  final  String LOG_NAME_PREFIX = "log_executor_";

    @Bean(name = "tradeTaskExecutor")
    public ThreadPoolTaskExecutor TradeExecutorCreate(){
        return getThreadPoolTaskExecutor(THREAD_NAME_PREFIX);
    }

    @Bean(name = "logTaskExecutor")
    public ThreadPoolTaskExecutor logExecutorCreate(){
        return getThreadPoolTaskExecutor(LOG_NAME_PREFIX);
    }

    private ThreadPoolTaskExecutor getThreadPoolTaskExecutor(String logNamePrefix) {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(50);
        threadPoolTaskExecutor.setMaxPoolSize(100);
        threadPoolTaskExecutor.setKeepAliveSeconds(5);
        threadPoolTaskExecutor.setQueueCapacity(100);
        threadPoolTaskExecutor.setThreadNamePrefix(logNamePrefix);
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

}

你可能感兴趣的:(线程,java,开发语言)