概述:
在java內建API中操作線程所用到的類為Thread。建立線程一般有兩種方式,
繼承Thread方式
實現Runnable方式,並以runnable作為target建立Thread
在Android中的耗時任務一般都需要另開線程來執行,常常需要用線程池來管理這些線程,實現控制線程數,重用,控制執行和取消等功能。 Java線程池
Java提供了四種線程池 newCachedThreadPool :
可緩衝線程池,若線程池長度超過處理需要,則回收空線程,否則建立新線程,線程規模可無限大。
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
當執行第二個任務時第一個任務已經完成,會複用執行第一個任務的線程,而不用每次建立線程。 newFixedThreadPool :
定長線程池,可控制線程最大並發數,超出的線程會在隊列中等待。
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
定長線程池的大小最好根據系統資源進行設定。如Runtime.getRuntime().availableProcessors()。 newScheduledThreadPool :
定長線程池,支援定時及週期性任務執行,類似Timer。
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);
使用執行個體:
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);//表示延遲1秒後每3秒執行一次。scheduledThreadPool.scheduleAtFixedRate(new Runnable() { @Override public void run() { System.out.println("delay 1 seconds, and excute every 3 seconds"); }}, 1, 3, TimeUnit.SECONDS);
newSingleThreadExecutor :
單線程 的線程池,支援FIFO, LIFO, 優先順序策略。
ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
通過觀察源碼,其中四種線程的建立都是建立一個ThreadPoolExecutor。其中ThreadPoolExecutor是ExecutorService介面的實作類別。 java.util.concurrent
此包是java的並發編程包,其下定義了三個Executor介面
Executor:一個運行新任務的簡單介面。
ExecutorService:擴充了Executor介面。添加了一些用來管理執行器生命週期和任務生命週期的方法。
ScheduledExecutorService:擴充了ExecutorService。支援Future和定期執行任務。
實作類別包括:ScheduledThreadPoolExecutor、ThreadPoolExecutor。
java中提供的四種線程池,除了ScheduledThreadPool使用的是ScheduledThreadPoolExecutor,其他均為ThreadPoolExecutor。 ThreadPoolExecutor
public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) {}
參數說明
corePoolSize :線程池的核心線程數。
maximumPoolSize :線程池所能容納的最大線程數。
keepAliveTime :非核心線程閑置時的逾時時間長度。超過該時間長度,非核心線程就會被回收。
unit :keepAliveTime的時間單位。
workQueue :線程池中的任務隊列。
threadFactory:線程工廠,預設值DefaultThreadFactory。
handler : 飽和策略,當線程池中的數量大於maximumPoolSize,對拒絕任務的處理策略,預設值ThreadPoolExecutor.AbortPolicy()。
參考:
Java並發教程(Oracle官方資料)
Trinea:Java(Android)線程池
Java多線程:ThreadPoolExecutor詳解
並發編程網 - ifeve.com
線程池ThreadPoolExecutor介紹