1. 程式人生 > >使用java自帶線程池

使用java自帶線程池

gin [] lse first lac pool multi head 所有

java提供自帶的線程池,而不需要自己去開發一個自定義線程池了。

線程池類ThreadPoolExecutor在包java.util.concurrent下

ThreadPoolExecutor threadPool= new ThreadPoolExecutor(10, 15, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());

第一個參數10 表示這個線程池初始化了10個線程在裏面工作
第二個參數15 表示如果10個線程不夠用了,就會自動增加到最多15個線程
第三個參數60 結合第四個參數TimeUnit.SECONDS,表示經過60秒,多出來的線程還沒有接到活兒,就會回收,最後保持池子裏就10個
第四個參數TimeUnit.SECONDS 如上
第五個參數 new LinkedBlockingQueue() 用來放任務的集合

execute方法用於添加新的任務
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 package multiplethread; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class TestThread { public static void
main(String[] args) throws InterruptedException { ThreadPoolExecutor threadPool= new ThreadPoolExecutor(10, 15, 60, TimeUnit.SECONDS, newLinkedBlockingQueue<Runnable>()); threadPool.execute(new Runnable(){ @Override public void
run() { // TODO Auto-generated method stub System.out.println("任務1"); } }); } }

使用java自帶線程池