Java通過Executors提供四種線程池,分別為:
newCachedThreadPool建立一個可緩衝線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則建立線程。
newFixedThreadPool 建立一個定長線程池,可控制線程最大並發數,超出的線程會在隊列中等待。
newScheduledThreadPool 建立一個定長線程池,支援定時及週期性任務執行。
newSingleThreadExecutor 建立一個單線程化的線程池,它只會用唯一的背景工作執行緒來執行任務,保證所有任務按照指定順序(FIFO, LIFO, 優先順序)執行。
newCachedThreadPool
public static void main(String[] args) {ExecutorService cachedThreadPool = Executors.newCachedThreadPool();for (int i = 0; i < 10; i++) {final int index = i;try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}cachedThreadPool.execute(new Runnable() {public void run() {System.out.println(index);}});}} 建立一個可緩衝線程池,如果線程池長度超過處理需要,可靈活回收空閑線程,若無可回收,則建立線程。
這裡的線程池是無限大的,當一個線程完成任務之後,這個線程可以接下來完成將要分配的任務,而不是建立一個新的線程,
java api 1.7 will reuse previously constructed threads when they are available.
newFixedThreadPool
public static void main(String[] args) {ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);for (int i = 0; i < 10; i++) {final int index = i;fixedThreadPool.execute(new Runnable() {public void run() {try {System.out.println(index);Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}}});}}
建立一個定長線程池,可控制線程最大並發數,超出的線程會在隊列中等待
定長線程池的大小最好根據系統資源進行設定。如Runtime.getRuntime().availableProcessors()
public static void main(String[] args) {ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);for (int i = 0; i < 10; i++) {scheduledThreadPool.schedule(new Runnable() {public void run() {System.out.println("delay 3 seconds");}}, 3, TimeUnit.SECONDS);}}
newSingleThreadExecutor
public static void main(String[] args) {ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();for (int i = 0; i < 10; i++) {final int index = i;singleThreadExecutor.execute(new Runnable() {public void run() {/*System.out.println(index);*/try {System.out.println(index);Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}}});}}
按順序來執行線程任務 但是不同於單線程,這個線程池只是只能存在一個線程,這個線程死後另外一個線程會補上