public class Main { public static void main(String[] args) { try { /// ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 200, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(5));//創建線程池 var executores = Executors.newCachedThreadPool();//創建線程池 ThreadDemo temp=new ThreadDemo("Hello");創建線程 executores.execute(temp);//將線程放入到線程池里面 System.out.println("Hello World!"); } catch (Exception e) { } } } class ThreadDemo extends Thread { private String threadName; ThreadDemo( String name) { threadName = name; System.out.println("Creating " + threadName ); } public void run() { System.out.println("Running " + threadName ); try { for(int i = 4; i > 0; i--) { System.out.println("Thread: " + threadName + ", " + i); // 讓線程睡眠一會 Thread.sleep(50); } }catch (InterruptedException e) { System.out.println("Thread " + threadName + " interrupted."); } System.out.println("Thread " + threadName + " exiting."); } }
其中
在java doc中,並不提倡我們直接使用ThreadPoolExecutor,而是使用Executors類中提供的幾個靜態方法來創建線程池:
|
|
Executors.newCachedThreadPool();
//創建一個緩沖池,緩沖池容量大小為Integer.MAX_VALUE
Executors.newSingleThreadExecutor();
//創建容量為1的緩沖池
Executors.newFixedThreadPool(
int
);
//創建固定容量大小的緩沖池
|
- setCorePoolSize:設置核心池大小(我理解的就是可以同時運行的最大線程數量,超過這個數量會等待該線程池內其他線程完成釋放后執行)
- setMaximumPoolSize:設置線程池最大能創建的線程數目大小
當線程池的任務緩存隊列已滿並且線程池中的線程數目達到MaximumPoolSize,如果還有任務到來就會采取任務拒絕策略,通常有以下四種策略:
ThreadPoolExecutor.AbortPolicy:丟棄任務並拋出RejectedExecutionException異常。ThreadPoolExecutor.DiscardPolicy:也是丟棄任務,但是不拋出異常。ThreadPoolExecutor.DiscardOldestPolicy:丟棄隊列最前面的任務,然后重新嘗試執行任務(重復此過程)ThreadPoolExecutor.CallerRunsPolicy:由調用線程處理該任務
線程池的關閉
ThreadPoolExecutor提供了兩個方法,用於線程池的關閉,分別是shutdown()和shutdownNow(),其中:
- shutdown():不會立即終止線程池,而是要等所有任務緩存隊列中的任務都執行完后才終止,但再也不會接受新的任務
- shutdownNow():立即終止線程池,並嘗試打斷正在執行的任務,並且清空任務緩存隊列,返回尚未執行的任務
參考資料:https://www.cnblogs.com/dolphin0520/p/3932921.html
