Java物件例項的鎖一共有四種狀態:無鎖,偏向鎖,輕量鎖和重量鎖。原始脫離框架的併發應用大部分都需要手動完成加鎖k16-0.html" target="_blank" >釋放,最直接的就是使用synchronized和volatile關鍵字對某個物件或者程式碼塊加鎖從而限制每次訪問的.次數,從物件之間的競爭也可以實現到物件之間的協作。但是這樣手動實現出來的應用不僅耗費時間而且效能表現往往又有待提升。
一、執行緒池結構圖
二、示例
定義執行緒介面
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)