JDK线程池简析

1.CachedThreadPool

    CachedThreadPool的建立方式java

ExecutorService executorService = Executors.newCachedThreadPool();
public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                    60L, TimeUnit.SECONDS,
                                    new SynchronousQueue<Runnable>());
}

    SynchronousQueue有2个方法须要注意,put和offer,put方法分状况来讲:假设线程A正在waiting 从SynchronousQueue取一个元素,此时put(e),则e会被A接走,put会立刻返回;假设没有线程正在waiting从SynchronousQueue取一个元素,此时put(e),则put(e)会阻塞当前的线程。put的特色是若是没有线程在waiting从SynchronousQueue取元素,则put(e)会阻塞当前线程。spa

    offer方法分状况来讲:假设线程A正在waiting 从SynchronousQueue取一个元素,此时offer(e),则e会被A接走,offer返回true;假设没有线程正在waiting从SynchronousQueue取一个元素,此时offer(e),则offer(e)不会阻塞当前的线程,会立刻返回,且返回false。offer特色是若是没有线程在waiting从SynchronousQueue取元素,则offer(e)不会阻塞当前线程。线程

 

   JDK的ThreadPoolExecutor的execute方法代码以下(若是不理解,建议先看下JDK中ThreadPoolExecutor的源码,理解工做原理)。若是提交的Runnable执行耗时较长,那么多数状况下没有waiting to receive的线程,因此图1中第二个红框处的workQueue.offer(command) 会立刻返回false,因此会进入第三个红框处,即在线程池中新增线程。这就是为何若是咱们提交的Runnable执行耗时较长,则会出现不少的线程,如图2所示。code

             

                                    图1 JDK中ThreadPoolExecutor的execute(...)源码源码

             

                            图2 设置每一个Runnable中睡眠700毫秒,则线程池建立了10个线程it

    使用场景:JDK的注释上说,用于short-lived task,这中线程池我在不少源码中看见过。class

    缺点:线程池中会出现大量的线程。原理

相关文章
相关标签/搜索