《Java 并发编程实战》笔记 - 线程池的使用
最后更新于
public static ExecutorService newFixedThreadPool(int nThreads) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>());
}public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}private static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
} +------------------------------------------------------------------------+
runnbale | +-----------------------+ |
-------->| True | +------+ +------+ | |
|--> workerCount < corePoolSize? ------------->| |Worker| |Worker| ... | |
runnbale | | new Worker() | +------+ +------+ | |
-------->| False | +-----------------------+ |
| | | | | ^ |
runnbale | | workQueue.take | |
-------->| | | | | | |
| | v v v | |
| | +---------------------------+ | |
| v True | +--------+ +--------+ | | |
| workQueue.offer? -------->| |Runnable| |Runnable| ... | | |
| | | +--------+ +--------+ | | |
| False | +---------------------------+ | |
| | BlockingQueue<Runnable> | |
| | | |
| V True | |
| workerCount < maximumPoolSize? ------------------------------+ |
| | new Worker() |
| False | |
| | |
| v |
| +-------------+------------+--------------+ |
| | | | | |
| v v v v |
| CallerRunsPolicy AbortPolicy DiscardPolicy DiscardOldestPolicy |
+------------------------------------------------------------------------+