如何在安卓中使用線程池(ThreadPoolExecutor)
標(biāo)簽(空格分隔): 翻譯計(jì)劃
原文鏈接地址:Using ThreadPoolExecutor in Android
這篇文章將會(huì)覆蓋線程池、線程池執(zhí)行者、和怎么把他們使用到安卓里面。我們將會(huì)介紹這些主題,并且會(huì)附有許多示例代碼。
線程池(Thread Pools)
一個(gè)線程池管理者一個(gè)工作線程池(線程池確定的個(gè)數(shù)取決于我們?nèi)绾螌?shí)現(xiàn)的)
一個(gè)任務(wù)隊(duì)列保持著等待的任務(wù),這些任務(wù)將會(huì)被線程池中的等待線程執(zhí)行。生產(chǎn)者把任務(wù)添加到隊(duì)列中,而工作線程作為消費(fèi)者,只要有空閑的線程準(zhǔn)備好執(zhí)行任務(wù),就從任務(wù)隊(duì)列中取出任務(wù)并且消耗掉它。
線程執(zhí)行者(ThreadPoolExecutor)
ThreadPoolExecutor則使用線程池中的一個(gè)線程來執(zhí)行給定的任務(wù)
創(chuàng)建一個(gè)線程執(zhí)行者:
ThreadPoolExecutor executor = ThreadPoolExecutor( int corePoolSize,
int maximumPoolSize,
long keepAliveTime,
TimeUnit unit,
BlockingQueue<Runnable> workQueue
);
這些參數(shù)的含義
- 1、corePoolSize
- 線程池中的最小線程個(gè)數(shù),最初的線程池個(gè)數(shù)初始化是0個(gè),但是當(dāng)我們把任務(wù)添加到隊(duì)列中的時(shí)候,一個(gè)新的線程將會(huì)被創(chuàng)建,如果有空線程,但是線程數(shù)低于corePoolSize,那么新的線程將會(huì)被繼續(xù)創(chuàng)建
- 2、maximumPoolSize
- 線程池中允許創(chuàng)建的最大線程個(gè)數(shù),如果這個(gè)數(shù)字超過了corePolSize,并且currentPoolSize>=corePoolSize,那么只有當(dāng)隊(duì)列滿的時(shí)候才會(huì)去創(chuàng)建新的工作線程。
- 3、keepAliveTime
- 線程存活時(shí)間,當(dāng)線程數(shù)大于核心線程(工作線程),那么非核心線程(多于的空閑線程)將等待新的任務(wù),如果這些線程在該參數(shù)定義的時(shí)間內(nèi)沒有得到任務(wù)去執(zhí)行,將會(huì)被銷毀。
- 4、unit
- 線程存活時(shí)間keepAliveTime的時(shí)間單位
- 5、workQueue
- 工作隊(duì)列,將會(huì)持有持續(xù)運(yùn)行任務(wù),這里將會(huì)展現(xiàn)BlockingQueue
安卓和Java中為什么會(huì)用到線程池
- 1、這是一個(gè)強(qiáng)大的任務(wù)執(zhí)行框架,支持隊(duì)列中的任務(wù)添加,任務(wù)取消和任務(wù)優(yōu)先級排序
- 2、它可以減少線程創(chuàng)建的開銷,因?yàn)樗麜?huì)在線程池中管理所需要的線程
在安卓中使用ThreadPoolExecutor
首先,創(chuàng)建一個(gè)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);
}
}
創(chuàng)建一個(gè)MainThreadExecutor
public class MainThreadExecutor implements Executor {
private final Handler handler = new Handler(Looper.getMainLooper());
@Override
public void execute(Runnable runnable) {
handler.post(runnable);
}
}
創(chuàng)建一個(gè)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;
}
}
現(xiàn)在在你的代碼邏輯中使用吧
/*
* 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.
}
});
}
通過這種方式,我們可以創(chuàng)建不同的線程池來服務(wù)于網(wǎng)絡(luò)任務(wù)/IO任務(wù)/(后臺(tái))耗時(shí)任務(wù)、還有其他任務(wù)。
如何取消任務(wù)
當(dāng)我們?nèi)∠粋€(gè)任務(wù)的時(shí)候,我們需要得到一個(gè)Future,而不是直接執(zhí)行,因此我們需要使用submit,這樣將會(huì)返回一個(gè)Future,然后我們就可以使用返回回來的Future來取消任務(wù).
/*
* 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);
如何對一個(gè)任務(wù)設(shè)置優(yōu)先級
假設(shè)一個(gè)任務(wù)隊(duì)列中有20個(gè)任務(wù),而我們創(chuàng)建的線程池只有四個(gè)可用于工作的線程,我們可以基于優(yōu)先級來執(zhí)行任務(wù),畢竟我們一次只能執(zhí)行4個(gè)任務(wù)。
假設(shè)我們需要在隊(duì)列中首先執(zhí)行最后一個(gè)任務(wù),我們可以為這個(gè)線程設(shè)置IMMEDIATE優(yōu)先級,以便于我們在隊(duì)列中獲取新任務(wù)的時(shí)候,將會(huì)執(zhí)行此任務(wù)(因?yàn)檫@個(gè)標(biāo)志的任務(wù)具有最高優(yōu)先級)
要設(shè)置任務(wù)的優(yōu)先級,我們需要?jiǎng)?chuàng)建一個(gè)線程池執(zhí)行器
創(chuàng)建枚舉優(yōu)先級
/**
* 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. 低級優(yōu)先級
*/
LOW,
/**
* Medium priority level. Used for warming of data that might soon get visible. 中端優(yōu)先級
*/
MEDIUM,
/**
* Highest priority level. Used for data that are currently visible on screen. 高優(yōu)先級
*/
HIGH,
/**
* Highest priority level. Used for data that are required instantly(mainly for emergency). 最高優(yōu)先級
*/
IMMEDIATE;
}
創(chuàng)建一個(gè)優(yōu)先級線程
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;
}
}
創(chuàng)建一個(gè)PriorityThreadPoolExecutor(優(yōu)先級線程執(zhí)行者)繼承于ThreadPoolExecutor,我們還需要?jiǎng)?chuàng)建一個(gè)PriorityFutureTask,實(shí)現(xiàn)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
);
}
}
給一個(gè)如何給一個(gè)任務(wù)設(shè)置優(yōu)先級的例子
/*
* 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.
}
});
}
通過這種方式,我們就可以創(chuàng)建一個(gè)具有優(yōu)先級的任務(wù),上述所有使用方式同樣適用于Java Applications
這里給一個(gè)我自己封裝的安卓網(wǎng)絡(luò)工作的依賴庫Android Networking Library
如果想知道更詳細(xì)的實(shí)現(xiàn),可以查看DefaultExecutorSupplier.java這個(gè)類在Android Networking here.
我希望這些知識(shí)對于你有些幫助
感謝您閱讀本文。
如果您發(fā)現(xiàn)它有用,請務(wù)必點(diǎn)擊下面的?推薦這篇文章。
如果想知道更多的關(guān)于程序設(shè)計(jì)方面的知識(shí), follow me and Mindorks ,以便于我們更新新的技術(shù)文章的時(shí)候會(huì)通知到你。
Check out all the Mindorks best articles here.
Also, Let’s become friends on Twitter, Linkedin, Github and Facebook.
當(dāng)然了最后的這些推薦都是需要翻墻的,這個(gè)就需要大家墻一下了哈.這里推薦給大家一個(gè)翻墻的網(wǎng)址,需要收費(fèi)的,但是非常便宜的(最低的套餐一個(gè)月15G/1.5元 一年才18(現(xiàn)在搞活動(dòng))),可以看一下