package com.aaa.threaddemo; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.ThreadPoolExecutor.AbortPolicy; /* 一 常見線程池之 * newCachedThreadDemo * 1 可以根據需要創建新的線程的線程池 * 2 舊的線程可用時,將重用他們。 第一個任務完成,第二個任務會復用第一個線程,不會新建線程 * 3 當舊的線程不可用時,才會創建新的線程。 終止並且從緩存中移除 60秒未使用的線程 * 4 所有該線程就算長時間保持空閑,也不會使用任何資源 * 5 任何任務來了就能執行,不需要等待 * * 場景? * 對於執行 許多短期異步的程序。 * 大量,耗時少的任務 * 可以提高效率 * 二 真實的 newCacheThreadPool() public static ExecutorService newCachedThreadPool() { return new ThreadPoolExecutor( 0, //核心線程數量 0 Integer.MAX_VALUE, //最大線程數量時Integer型的最大值,是2147483647。 60L, //非核心線程生存時間 60秒 TimeUnit.SECONDS, //空閑時間單位 秒 new SynchronousQueue<Runnable>()); //等待隊列 SynchronousQueue } 三 SynchronousQueue 隊列是個啥? 1.是阻塞隊列 BlockingQueue 的一種,所以線程上是安全的 2.SynchronousQueue的容量是0,不存儲任何元素 3.更是在線程之間移交任務 在兩個線程之間傳遞同一個對象 當有item 來的時候, insert操作。需要等待其他線程來接收。其他線程做remove操作。 當刪除 item, remove操作,也是一樣的。 四 拒絕策略 默認的 AbortPolicy。 public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) { this(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, defaultHandler); } private static final RejectedExecutionHandler defaultHandler = new AbortPolicy(); 和它相關的任務 都不執行 線程池默認的拒絕方式 * */ public class CachedThreadPoolDemo { public static void main(String[] args) { ExecutorService cachePool = Executors.newCachedThreadPool(); //創建可以緩存的線程池 //來6個線程試一下 CacheThread cacheThread = new CacheThread(); CacheThread cacheThread2 = new CacheThread(); CacheThread cacheThread3 = new CacheThread(); CacheThread cacheThread4 = new CacheThread(); CacheThread cacheThread5 = new CacheThread(); CacheThread cacheThread6 = new CacheThread(); cachePool.execute(cacheThread); cachePool.execute(cacheThread2); cachePool.execute(cacheThread3); cachePool.execute(cacheThread4); cachePool.execute(cacheThread5); cachePool.execute(cacheThread6); Runnable task = new Runnable() { public void run() { System.out.println("new 一個 runnable接口, 實現多線程"); System.out.println("當前執行線程的名字" + Thread.currentThread().getName()); } }; cachePool.execute(task); //線程池中執行任務 cachePool.shutdown(); //漸進式的關閉線程池 } } class CacheThread extends Thread{ @Override public void run() { System.out.println("當前執行線程的名字" + Thread.currentThread().getName()); } }
看下結果

讓線程睡一會

