多執行緒是程式設計師面試時常常會面對的問題,對多執行緒概念的掌握和理解水平,也常常被用來衡量一個人的程式設計實力。不錯,普通的.多執行緒已經不容易了。
一、執行緒池結構圖
二、示例
定義執行緒介面
6public class MyThread extends Thread {@Overridepublicvoid run() {tln(entThread()ame() + "正在執行");}}
1:newSingleThreadExecutor
10ExecutorService pool = Executors. newSingleThreadExecutor();Thread t1 = new MyThread();Thread t2 = new MyThread();Thread t3 = new MyThread();//將執行緒放入池中進行執行ute(t1);ute(t2);ute(t3);//關閉執行緒池down();
輸入結果:
3pool-1-thread-1正在執行pool-1-thread-1正在執行pool-1-thread-1正在執行
2:newFixedThreadPool
13ExecutorService pool = ixedThreadPool(3);Thread t1 = new MyThread();Thread t2 = new MyThread();Thread t3 = new MyThread();Thread t4 = new MyThread();Thread t5 = new MyThread();//將執行緒放入池中進行執行ute(t1);ute(t2);ute(t3);ute(t4);ute(t5);down();
輸入結果:
4pool-1-thread-1正在執行pool-1-thread-2正在執行pool-1-thread-1正在執行pool-1-thread-2正在執行
3 :newCachedThreadPool
14ExecutorService pool = achedThreadPool();Thread t1 = new MyThread();Thread t2 = new MyThread();Thread t3 = new MyThread();Thread t4 = new MyThread();Thread t5 = new MyThread();//將執行緒放入池中進行執行ute(t1);ute(t2);ute(t3);ute(t4);ute(t5);//關閉執行緒池down();
輸入結果:
5pool-1-thread-2正在執行pool-1-thread-4正在執行pool-1-thread-3正在執行pool-1-thread-1正在執行pool-1-thread-5正在執行
4 :ScheduledThreadPoolExecutor
14ScheduledExecutorService pool = cheduledThreadPool(2);duleAtFixedRate(new Runnable() {//每隔一段時間就觸發異常 @Override public void run() { //throw new RuntimeException(); tln("================"); }}, 1000, 2000, ISECONDS);duleAtFixedRate(new Runnable() {//每隔一段時間列印系統時間,證明兩者是互不影響的 @Override public void run() { tln("+++++++++++++++++"); }}, 1000, 2000, ISECONDS);
輸入結果:
4================+++++++++++++++++++++++++++++++++++++++++++++++++++
三、執行緒池核心引數
corePoolSize : 池中核心的執行緒數
maximumPoolSize : 池中允許的最大執行緒數。
keepAliveTime : 當執行緒數大於核