標籤:線程池 解決 沒有 結束 img schedule 大小 static main
線程池
線程池的思想
線程池的概念與Executors類的應用
> 建立固定大小的線程池
> 建立緩衝線程池
> 建立單一線程池(如何?線程死掉後重新啟動?)
關閉線程池
> shutdown 與 shutdownNow的比較
用線程池啟動定時器
> 調用ScheduleExecutorService 的 schedule 方法,返回的ScheduleFuture對象可以取消任務。
> 支援間隔重複任務的定時方式,不直接支援決定定時的方法,需要轉換成相對時間方式。
public class ThreadPoolTest { public static void main(String[] args) {// ExecutorService threadPool = Executors.newFixedThreadPool(3); //建立一個固定大小的線程池,線程池中有3個線程可以同時服務 //緩衝線程池 線程池中的線程數是動態變化的,當所有線程處於服務狀態時,還有需要被服務的任務,自動增加一個線程進行服務 //當任務執行完畢,線程處於空閑一段時間,逾時後則自動回收銷毀線程// ExecutorService threadPool = Executors.newCachedThreadPool(); //建立一個只有一個線程的線程池,當這個線程掛掉時,可以自動產生一個線程來代替 //可以解決一個網上很多人問的問題(如何?線程死掉後重新啟動?) ExecutorService threadPool = Executors.newSingleThreadExecutor(); for(int i = 0;i<10;i++){ //往線程池中扔10個任務,同時被服務的有3個,其他線程進行排隊 final int task = i; threadPool.execute(new Runnable() { //往線程池中扔了一個任務 @Override public void run() { for(int j = 0;j<10;j++){ System.out.println(Thread.currentThread().getName()+" is loop of "+ j + "the task of "+task); } } }); } System.out.println("all of 10 tasks have committed"); //上述代碼執行完後 沒有結束,線程池中有3個線程一直存在,所以程式不會結束 //可以使用 threadPool.shutdown() threadPool.shutdown(); //當線程池中線程執行完所有任務,所有線程處於空閑狀態時,幹掉所有線程,程式自結束// threadPool.shutdownNow(); //立即把池子中所有線程幹掉,無論任務是否幹完 }}
用線程池啟動定時器
Executors.newScheduledThreadPool(3).schedule( new Runnable() { @Override public void run() { System.out.println("bombing!"); } }, 10, TimeUnit.SECONDS);
還可以在上述代碼中添加固定頻率
//固定頻率 10秒後觸發,每隔兩秒後執行一次 Executors.newScheduledThreadPool(3).scheduleAtFixedRate( new Runnable() { @Override public void run() { System.out.println("bombing!"); } }, 10, 2, TimeUnit.SECONDS); //在使用scheduleAtFixedRate 時java api沒有提供在某個時間點觸發,但API中提示可以通過計算,得到觸發的事件點 // For example, to schedule at a certain future date, // you can use: schedule(task, date.getTime() - System.currentTimeMillis(), TimeUnit.MILLISECONDS).
Java多線程與並發庫進階應用程式-線程池