糯米文學吧

位置:首頁 > 計算機 > java語言

什麼是java線程池框架

java語言9.95K

多線程是程序員面試時常常會面對的問題,對多線程概念的掌握和理解水平,也常常被用來衡量一個人的編程實力。不錯,普通的.多線程已經不容易了。

什麼是java線程池框架

一、線程池結構圖

二、示例

定義線程接口

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 : 當線程數大於核

標籤:JAVA 線程 框架