您的位置:首页 > 移动开发 > Android开发

Android 多线程之四种线程池

2017-04-16 19:05 543 查看

Android中的四种线程池.

Android中常用有四种线程池,他们都是直接或者间接配置ThreadPoolExecutor 来实现自己的功能的.

1 FixedThreadPool

通过Executors 的newFixedThreadPool 方法来创建.

线程数量固定.

线程处于空闲状态时, 线程也不会被回收,除非线程池关闭了.正是这个原因所以它能够更加快速第响应外界请求.

当所有的线程都处于活动状态时, 新任务处于等待状态, 直到有线程空闲.

没有超时机制

没有任务熟练限制.

newFixedThreadPool方法源码

public static ExecutorService newFixedThreadPool(int nThreads, ThreadFactory threadFactory) {
return new ThreadPoolExecutor(nThreads, nThreads,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(),
threadFactory);
}


2 CachedThreadPool

通过Executors的newCachedThreadPool 来创建, 它是一种线程数量不定的线程池,他只有非核心线程并且最大线程数为integer.MAX_VALUE.

当线程池中的活动都处于活动状态时,会直接创建新的线程来处理任务.否则就利用空闲线程来处理任务.

超时时间是 60s ,线程闲置60s就会被回收.

这种线程适合大量的耗时较小的任务.

newCachedThreadPool源码

public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
}


3 ScheduledThreadPool

通过Executors的newScheduledThreadPool方法来创建.

核心线程数是固定的,非核心线程数没有限制.当非核心线程一旦闲置就会被立即回收.

ScheduledThreadPool主要用来执行定时任务和具有固定周期的重复任务.

newScheduledThreadPool源码

public static ScheduledExecutorService newScheduledThreadPool(
int corePoolSize, ThreadFactory threadFactory) {
return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);
}


4 SingleThreadPool

通过Executors的newSingleThreadExecutor方法创建.

只有一个核心线程,他可以确保所有的任务都在同一个线程中顺序执行.

他可以统一所有的外界任务到一个线程中,这样可以避免线程同步问题.

newSingleThreadExecutor源码

public static ExecutorService newSingleThreadExecutor() {
return new FinalizableDelegatedExecutorService
(new ThreadPoolExecutor(1, 1,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>()));
}


四种常用线程池的用法

由于与Android 系统已经对线程池进行了一层封装因此,我在使用的时候就简单了很多,只需要简单的配置即可。

private void threadPoolTest() {
// 创建任务
Runnable command = new Runnable() {
@Override
public void run() {
Log.d(TAG, "run: " + Thread.currentThread().getId());
SystemClock.sleep(2000);
}
};
// FixedThreadPool
ExecutorService fixed = Executors.newFixedThreadPool(4);
fixed.execute(command);
// Cached
ExecutorService cached = Executors.newCachedThreadPool();
cached.execute(command);
// Scheduled
ScheduledExecutorService scheduled = Executors.newScheduledThreadPool(4);
// 2000 ms 后执行
scheduled.schedule(command, 2000, TimeUnit.MILLISECONDS);
// 延时 10 后每隔 1000ms 执行一次
scheduled.scheduleAtFixedRate(command, 10, 1000, TimeUnit.MICROSECONDS);
// Single
ExecutorService single = Executors.newSingleThreadExecutor();
single.execute(command);
}


总结

在开发中根据具体的使用场景可以根据前面的介绍选择合适的线程池。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息