美文网首页
ThreadPoolExecutor线程池

ThreadPoolExecutor线程池

作者: jsjack_wang | 来源:发表于2018-01-19 15:28 被阅读0次
    1.ThreadPoolExecutor继承结构(具体可查API)
    --Executor (interface)
        --ExecutorService (interface)
            --AbstractExecutorService (abstract class)
                --ThreadPoolExecutor
    
    2.ThreadPoolExecutor常用API
    2.1 线程池实例化方法,共4个这里看最复杂的一个
    public ThreadPoolExecutor(int corePoolSize,
                              int maximumPoolSize,
                              long keepAliveTime,
                              TimeUnit unit,
                              BlockingQueue<Runnable> workQueue,
                              ThreadFactory threadFactory,
                              RejectedExecutionHandler handler);
    corePoolSize:核心线程数
    maximumPoolSize:最大线程数
    keepAliveTime:回收空闲线程的时间(默认回收大于核心线程数的部分)
    unit:回收空闲线程时间的单位
    workQueue:缓存队列,缓存尚未执行的Runnable
    threadFactory:线程创建工程
    handler:拒绝处理任务时的策略
    
    2.2 execute执行线程
    void execute(Runnable command);
    
    2.3 shutdown执行完所有任务 关闭线程池
    void shutdown();
    

    注意:具体每一个参数使用参考官方文档

    3.看看如下的小栗子
    public class ThreadPoolTest {
        public static void main(String[] args) {
            ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 5, 1, TimeUnit.MINUTES, new LinkedBlockingDeque<>());
            for (int index = 0; index < 30; index ++) {
                threadPoolExecutor.execute(new Task(index));
            }
            threadPoolExecutor.shutdown();
        }
    }
    
    class Task implements Runnable {
        private int index;
        public Task(int index) {
            this.index = index;
        }
        @Override
        public void run() {
            System.out.println(index + "正在执行...");
            try {
                Thread.sleep(2000);
            } catch (Exception e) {
            }
            System.out.println(index + "执行结束...");
        }
    }
    
    4.一般来说我们不推荐直接使用ThreadPoolExecutor, 而是使用Executors创建线程池,例如
    public static ExecutorService newSingleThreadExecutor();
    public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory);
    public static ExecutorService newCachedThreadPool();
    
    5.总结
    线程池还有很多其他的API,也就不一一介绍,有空还是要多看看源码和API文档
    
    源码地址:https://gitee.com/jsjack_wang/JavaDemo
    推荐博客:http://www.importnew.com/19011.html

    相关文章

      网友评论

          本文标题:ThreadPoolExecutor线程池

          本文链接:https://www.haomeiwen.com/subject/ieoooxtx.html