old《1.1.7 线程池应用及实现原理剖析》

old《1.1.7 线程池应用及实现原理剖析》
为什么ThreadPoolExecutor使用的是BlockingQueue?参考不怕难之BlockingQueue及其实现,因为:
old《1.1.7 线程池应用及实现原理剖析》
入队方法比如有:
offer(E e):如果队列没满,立即返回true; 如果队列满了,立即返回false–>不阻塞
put(E e):如果队列满了,一直阻塞,直到队列不满了或者线程被中断–>阻塞
JDK文档对put(E e)的描述:Inserts the specified element into this queue, waiting if necessary for space to become available. Queue类中无此方法。

出队方法比如有:
poll():如果没有元素,直接返回null;如果有元素,出队
take():如果队列空了,一直阻塞,直到队列不为空或者线程被中断–>阻塞
JDK文档对take()的描述:Retrieves and removes the head of this queue, waiting if necessary until an element becomes available. Queue类中无此方法。

Executors.newCachedThreadPool()所使用的SynchronousQueue是BlockingQueue的一种特殊实现,JDK文档对它有如下描述:
A blocking queue in which each insertoperation must wait for a corresponding remove operation by anotherthread, and vice versa. A synchronous queue does not have anyinternal capacity, not even a capacity of one. You cannot peek at a synchronous queue because an element is onlypresent when you try to remove it; you cannot insert an element(using any method) unless another thread is trying to remove it;you cannot iterate as there is nothing to iterate.

为什么Executors.newCachedThreadPool()使用SynchronousQueue:
old《1.1.7 线程池应用及实现原理剖析》