Java Spring程序员java进阶干货

线程池原理及其使用

2017-08-19  本文已影响88人  jiajun_geek

线程池

线程池的优点

线程池原理

ThreadPoolExecutor构造参数

ThreadPoolExecutor重要方法

线程池状态

volatile int runState;
static final int RUNNING    = 0;
static final int SHUTDOWN   = 1;
static final int STOP       = 2;
static final int TERMINATED = 3;

源码分析

public void execute(Runnable command) {
    if (command == null)
        throw new NullPointerException();
    if (poolSize >= corePoolSize || !addIfUnderCorePoolSize(command)) {
        if (runState == RUNNING && workQueue.offer(command)) {
            if (runState != RUNNING || poolSize == 0)
                ensureQueuedTaskHandled(command);
        }
        else if (!addIfUnderMaximumPoolSize(command))
            reject(command); // is shutdown or saturated
    }
}

配置线程池

线程池使用

public static void main(String[] args)
    {
        
        final Vector<Integer> vector = new Vector<Integer>();
        //corePoolSize,maximumPoolSize,keepAliveTime,TimeUnit,BlockingQueue
        ThreadPoolExecutor tp = new ThreadPoolExecutor(5, 10, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(10));
        final Random random = new Random();
        System.out.println(tp.getPoolSize());
        for (int i = 0; i < 20; i++)
        {
            tp.execute(new Runnable()
            {
                public void run()
                {
                    vector.add(random.nextInt());
                    
                }
            });
        }
        
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
        tp.shutdown();
        System.out.println("已完成的任务:"+tp.getCompletedTaskCount());
        System.out.println("活动的线程数:"+tp.getActiveCount());
        System.out.println("list大小:"+vector.size());
    }
public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}
public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>()));
}
public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

我觉得分享是一种精神,分享是我的乐趣所在,不是说我觉得我讲得一定是对的,我讲得可能很多是不对的,但是我希望我讲的东西是我人生的体验和思考,是给很多人反思,也许给你一秒钟、半秒钟,哪怕说一句话有点道理,引发自己内心的感触,这就是我最大的价值。(这是我喜欢的一句话,也是我写博客的初衷)

作者:jiajun 出处: http://www.cnblogs.com/-new/

上一篇下一篇

猜你喜欢

热点阅读