如何在安卓中使用線程池(ThreadPoolExecutor)
標簽(空格分隔): 翻譯計劃
原文鏈接地址:Using ThreadPoolExecutor in Android
這篇文章將會覆蓋線程池、線程池執行者、和怎么把他們使用到安卓里面。我們將會介紹這些主題,并且會附有許多示例代碼。
線程池(Thread Pools)
一個線程池管理者一個工作線程池(線程池確定的個數取決于我們如何實現的)
一個任務隊列保持著等待的任務,這些任務將會被線程池中的等待線程執行。生產者把任務添加到隊列中,而工作線程作為消費者,只要有空閑的線程準備好執行任務,就從任務隊列中取出任務并且消耗掉它。
線程執行者(ThreadPoolExecutor)
ThreadPoolExecutor則使用線程池中的一個線程來執行給定的任務
創建一個線程執行者:
ThreadPoolExecutor executor = ThreadPoolExecutor( int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue
);
這些參數的含義
- 1、corePoolSize
- 線程池中的最小線程個數,最初的線程池個數初始化是0個,但是當我們把任務添加到隊列中的時候,一個新的線程將會被創建,如果有空線程,但是線程數低于corePoolSize,那么新的線程將會被繼續創建
- 2、maximumPoolSize
- 線程池中允許創建的最大線程個數,如果這個數字超過了corePolSize,并且currentPoolSize>=corePoolSize,那么只有當隊列滿的時候才會去創建新的工作線程。
- 3、keepAliveTime
- 線程存活時間,當線程數大于核心線程(工作線程),那么非核心線程(多于的空閑線程)將等待新的任務,如果這些線程在該參數定義的時間內沒有得到任務去執行,將會被銷毀。
- 4、unit
- 線程存活時間keepAliveTime的時間單位
- 5、workQueue
- 工作隊列,將會持有持續運行任務,這里將會展現BlockingQueue
安卓和Java中為什么會用到線程池
- 1、這是一個強大的任務執行框架,支持隊列中的任務添加,任務取消和任務優先級排序
- 2、它可以減少線程創建的開銷,因為他會在線程池中管理所需要的線程
在安卓中使用ThreadPoolExecutor
首先,創建一個PriorityThreadFactory
public class PriorityThreadFactory implements ThreadFactory {
private final int mThreadPriority;
public PriorityThreadFactory(int threadPriority) {
mThreadPriority = threadPriority;
}
@Override
public Thread newThread(final Runnable runnable) {
Runnable wrapperRunnable = new Runnable() {
@Override
public void run() {
try {
Process.setThreadPriority(mThreadPriority);
} catch (Throwable t) {
}
runnable.run();
}
};
return new Thread(wrapperRunnable);
}
}
創建一個MainThreadExecutor
public class MainThreadExecutor implements Executor {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override
public void execute(Runnable runnable) {
handler.post(runnable);
}
}
創建一個DefaultExecutorSupplier
/*
* Singleton class for default executor supplier
*/
public class DefaultExecutorSupplier{
/*
* Number of cores to decide the number of threads
*/
public static final int NUMBER_OF_CORES = Runtime.getRuntime().availableProcessors();
/*
* thread pool executor for background tasks
*/
private final ThreadPoolExecutor mForBackgroundTasks;
/*
* thread pool executor for light weight background tasks
*/
private final ThreadPoolExecutor mForLightWeightBackgroundTasks;
/*
* thread pool executor for main thread tasks
*/
private final Executor mMainThreadExecutor;
/*
* an instance of DefaultExecutorSupplier
*/
private static DefaultExecutorSupplier sInstance;
/*
* returns the instance of DefaultExecutorSupplier
*/
public static DefaultExecutorSupplier getInstance() {
if (sInstance == null) {
synchronized(DefaultExecutorSupplier.class){
sInstance = new DefaultExecutorSupplier();
}
return sInstance;
}
/*
* constructor for DefaultExecutorSupplier
*/
private DefaultExecutorSupplier() {
// setting the thread factory
ThreadFactory backgroundPriorityThreadFactory = new
PriorityThreadFactory(Process.THREAD_PRIORITY_BACKGROUND);
// setting the thread pool executor for mForBackgroundTasks;
mForBackgroundTasks = new ThreadPoolExecutor(
NUMBER_OF_CORES * 2,
NUMBER_OF_CORES * 2,
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(),
backgroundPriorityThreadFactory
);
// setting the thread pool executor for mForLightWeightBackgroundTasks;
mForLightWeightBackgroundTasks = new ThreadPoolExecutor(
NUMBER_OF_CORES * 2,
NUMBER_OF_CORES * 2,
60L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(),
backgroundPriorityThreadFactory
);
// setting the thread pool executor for mMainThreadExecutor;
mMainThreadExecutor = new MainThreadExecutor();
}
/*
* returns the thread pool executor for background task
*/
public ThreadPoolExecutor forBackgroundTasks() {
return mForBackgroundTasks;
}
/*
* returns the thread pool executor for light weight background task
*/
public ThreadPoolExecutor forLightWeightBackgroundTasks() {
return mForLightWeightBackgroundTasks;
}
/*
* returns the thread pool executor for main thread task
*/
public Executor forMainThreadTasks() {
return mMainThreadExecutor;
}
}
現在在你的代碼邏輯中使用吧
/*
* Using it for Background Tasks
*/
public void doSomeBackgroundWork(){
DefaultExecutorSupplier.getInstance().forBackgroundTasks()
.execute(new Runnable() {
@Override
public void run() {
// do some background work here.
}
});
}
/*
* Using it for Light-Weight Background Tasks
*/
public void doSomeLightWeightBackgroundWork(){
DefaultExecutorSupplier.getInstance().forLightWeightBackgroundTasks()
.execute(new Runnable() {
@Override
public void run() {
// do some light-weight background work here.
}
});
}
/*
* Using it for MainThread Tasks
*/
public void doSomeMainThreadWork(){
DefaultExecutorSupplier.getInstance().forMainThreadTasks()
.execute(new Runnable() {
@Override
public void run() {
// do some Main Thread work here.
}
});
}
通過這種方式,我們可以創建不同的線程池來服務于網絡任務/IO任務/(后臺)耗時任務、還有其他任務。
如何取消任務
當我們取消一個任務的時候,我們需要得到一個Future,而不是直接執行,因此我們需要使用submit,這樣將會返回一個Future,然后我們就可以使用返回回來的Future來取消任務.
/*
* Get the future of the task by submitting it to the pool
*/
Future future = DefaultExecutorSupplier.getInstance().forBackgroundTasks()
.submit(new Runnable() {
@Override
public void run() {
// do some background work here.
}
});
/*
* cancelling the task
*/
future.cancel(true);
如何對一個任務設置優先級
假設一個任務隊列中有20個任務,而我們創建的線程池只有四個可用于工作的線程,我們可以基于優先級來執行任務,畢竟我們一次只能執行4個任務。
假設我們需要在隊列中首先執行最后一個任務,我們可以為這個線程設置IMMEDIATE優先級,以便于我們在隊列中獲取新任務的時候,將會執行此任務(因為這個標志的任務具有最高優先級)
要設置任務的優先級,我們需要創建一個線程池執行器
創建枚舉優先級
/**
* Priority levels
*/
public enum Priority {
/**
* NOTE: DO NOT CHANGE ORDERING OF THOSE CONSTANTS UNDER ANY CIRCUMSTANCES.
* Doing so will make ordering incorrect.
*/
/**
* Lowest priority level. Used for prefetches of data. 低級優先級
*/
LOW,
/**
* Medium priority level. Used for warming of data that might soon get visible. 中端優先級
*/
MEDIUM,
/**
* Highest priority level. Used for data that are currently visible on screen. 高優先級
*/
HIGH,
/**
* Highest priority level. Used for data that are required instantly(mainly for emergency). 最高優先級
*/
IMMEDIATE;
}
創建一個優先級線程
public class PriorityRunnable implements Runnable {
private final Priority priority;
public PriorityRunnable(Priority priority) {
this.priority = priority;
}
@Override
public void run() {
// nothing to do here.
}
public Priority getPriority() {
return priority;
}
}
創建一個PriorityThreadPoolExecutor(優先級線程執行者)繼承于ThreadPoolExecutor,我們還需要創建一個PriorityFutureTask,實現Comparable<PriorityFutureTask>接口
public class PriorityThreadPoolExecutor extends ThreadPoolExecutor {
public PriorityThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime,
TimeUnit unit, ThreadFactory threadFactory) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit,new PriorityBlockingQueue<Runnable>(), threadFactory);
}
@Override
public Future<?> submit(Runnable task) {
PriorityFutureTask futureTask = new PriorityFutureTask((PriorityRunnable) task);
execute(futureTask);
return futureTask;
}
private static final class PriorityFutureTask extends FutureTask<PriorityRunnable>
implements Comparable<PriorityFutureTask> {
private final PriorityRunnable priorityRunnable;
public PriorityFutureTask(PriorityRunnable priorityRunnable) {
super(priorityRunnable, null);
this.priorityRunnable = priorityRunnable;
}
/*
* compareTo() method is defined in interface java.lang.Comparable and it is used
* to implement natural sorting on java classes. natural sorting means the the sort
* order which naturally applies on object e.g. lexical order for String, numeric
* order for Integer or Sorting employee by there ID etc. most of the java core
* classes including String and Integer implements CompareTo() method and provide
* natural sorting.
*/
@Override
public int compareTo(PriorityFutureTask other) {
Priority p1 = priorityRunnable.getPriority();
Priority p2 = other.priorityRunnable.getPriority();
return p2.ordinal() - p1.ordinal();
}
}
}
首先,在DefaultExecutorSupplier,而不是ThreadPoolExecutor中,向一下使用方式使用PriorityThreadPoolExecutor.
public class DefaultExecutorSupplier{
private final PriorityThreadPoolExecutor mForBackgroundTasks;
private DefaultExecutorSupplier() {
mForBackgroundTasks = new PriorityThreadPoolExecutor(
NUMBER_OF_CORES * 2,
NUMBER_OF_CORES * 2,
60L,
TimeUnit.SECONDS,
backgroundPriorityThreadFactory
);
}
}
給一個如何給一個任務設置優先級的例子
/*
* do some task at high priority
*/
public void doSomeTaskAtHighPriority(){
DefaultExecutorSupplier.getInstance().forBackgroundTasks()
.submit(new PriorityRunnable(Priority.HIGH) {
@Override
public void run() {
// do some background work here at high priority.
}
});
}
通過這種方式,我們就可以創建一個具有優先級的任務,上述所有使用方式同樣適用于Java Applications
這里給一個我自己封裝的安卓網絡工作的依賴庫Android Networking Library
如果想知道更詳細的實現,可以查看DefaultExecutorSupplier.java這個類在Android Networking here.
我希望這些知識對于你有些幫助
感謝您閱讀本文。
如果您發現它有用,請務必點擊下面的?推薦這篇文章。
如果想知道更多的關于程序設計方面的知識, follow me and Mindorks ,以便于我們更新新的技術文章的時候會通知到你。
Check out all the Mindorks best articles here.
Also, Let’s become friends on Twitter, Linkedin, Github and Facebook.
當然了最后的這些推薦都是需要翻墻的,這個就需要大家墻一下了哈.這里推薦給大家一個翻墻的網址,需要收費的,但是非常便宜的(最低的套餐一個月15G/1.5元 一年才18(現在搞活動)),可以看一下