android 线程池简书,笔记:Android线程和线程池

Android线程和线程池

Android中的线程操作相关的类有

AsyncTask IntentService HandleThread

AsyncTask

AsyncTask必须在主线程中初始化

Android 3.0开始 AsyncTask默认使用串行方式执行任务队列,即单线程串行,但可定制线程池并行执行通过executOnExecutor()。

主要是SerialExcutor负责任务的排队,THREAD_POOL_EXCUTOR负责真正的任务执行。

executor()方法必须在UI线程中执行

一个AsyncTask对象只能执行一次,否则会报错

AsyncTask中有用到抽象工厂模式(多线程环境下工厂类创建线程)

AsyncTask中对任务包装主要是FutureTask

FutureTask可用于异步获取执行结果或取消执行任务的场景。通过传入Runnable或者Callable的任务给FutureTask,直接调用其run方法或者放入线程池执行,之后可以在外部通过FutureTask的get方法异步获取执行结果,因此,FutureTask非常适合用于耗时的计算,主线程可以在完成自己的任务后,再去获取结果。另外,FutureTask还可以确保即使调用了多次run方法,它都只会执行一次Runnable或者Callable任务,或者通过cancel取消FutureTask的执行等。

HandleThread

继承自Thread,主要是内部创建了Looper,关联Looper,不用手动创建Thread中prepare Looper和loop了。

IntentService

一个抽象类,继承自Service

适用于执行后台耗时任务,任务停止后,Service自动停止

由于它是服务,它比其他线程优先级高很多,不容易被系统kill

内部它封装了HandlerThread 和Handler,从onCreate中可以看得出

@Override

public void onCreate() {

// TODO: It would be nice to have an option to hold a partial wakelock

// during processing, and to have a static startService(Context, Intent)

// method that would launch the service & hand off a wakelock.

super.onCreate();

HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");

thread.start();

mServiceLooper = thread.getLooper();

mServiceHandler = new ServiceHandler(mServiceLooper);

}

IntentSerivce 通过调用startService传递Intent到onStartCommand,onStartCommand会通过Handle发送Message至IntentService内部的HandleThread中,根据Intent

中携带的参数,调用重写的onHandleIntent处理任务,onHandleIntent执行完毕后,执行stopSelf(startId)

这里为何调用stopSelf(startId) 它与stopSelf()区别

stopSelf(startId)不会立即停止当前Serivce,而是等待所有Intent都执行完毕后才会终止服务,每调用一次startService(Intent)都会调用一次onStartCommand传递Intent。

stopSelf()会立即停止服务

因为IntentService内部HandleThread的消息机制,所以,传递给IntentService的Intent任务也是顺序执行的。

Android中的线程池

public ThreadPoolExecutor(int corePoolSize,

int maximumPoolSize,

long keepAliveTime,

TimeUnit unit,

BlockingQueue workQueue,

ThreadFactory threadFactory)

corePoolSize: 核心线程数,默认情况下一直存活的线程,即使空闲状态下,如果将ThreadPoolExecutor的allowCoreThreadTimeOut属性设置为true,则闲置的线程在等待新任务到来时会有超时策略,超时时间由keepAliveTime来决定,当超时后,核心线程就会被终止

maximumPoolSize: 线程池所能容纳的最大线程数,当活动线程数达到这个数值后,后续的新任务将会被阻塞

keepAliveTime:非核心线程线程闲置时间超时时长。超过这个时长,线程将会被回收

unit:指定keepAliveTime所用的时间单位

workQueue:线程池中的任务队列,通过execute提交的Runnable对象会存储在这个队列中。

threadFactory:线程工厂,为线程池创建新的线程,为一个接口。

ThreadpoolExecutor 执行任务大致规则:

如果线程池中的核心线程数未达到核心线程的数量,那么会启动核心线程来执行任务。

如果线程池中的线程数量已经达到或超过核心线程数量,那么新来的任务会被插入到任务队列中排队等待执行

如果在步骤2中无法将任务插入到任务队列,这是由于任务队列已经满了,这个时候如果线程数量未达到线程池规定的最大数量,那么会立刻启动一个非核心线程来执行任务。

如果步骤3中的线程数量已经达到线程池的最大值,则拒绝此任务,ThreadPoolExecutor会调用RejectedExecutionHandler的rejectExecution方法通知调用者。具体可以看源码.

AsyncTask中的任务队列容量为128

Android中四种常用的线程池:

FixedThreadPool

Executors.newFixedThreadPool()

public static ExecutorService newFixedThreadPool(int nThreads) {

return new ThreadPoolExecutor(nThreads, nThreads,

0L, TimeUnit.MILLISECONDS,

new LinkedBlockingQueue());

}

线程数量固定,当线程处于空闲时,线程并不会被回收,除非线程池关闭,当所有线程处于活动状态时,新任务就会处于等待状态,直到有线程空闲下来.

由于FixedThreadPool只有核心线程,并且不会被♻️,所以它会更加快速的响应外界的请求。没有超时机制,任务队列大小也没闲置。

CachedThreadPool

public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {

return new ThreadPoolExecutor(0, Integer.MAX_VALUE,

60L, TimeUnit.SECONDS,

new SynchronousQueue(),

threadFactory);

它是一个线程数量不固定的线程池,当线程池中的线程都处于活动状态,线程池会创建新的线程来处理任务,否者就会利用空闲的线程来处理新任务

空闲的线程超过60秒就会被回收

SynchronousQueue很特殊,无法存储元素的队列。

该线程池适合大量耗时较少的任务,当整个线程池中的线程都处于空闲状态时,线程会因超时而被♻️,这时它几乎不占用任何资源

ScheduledThreadPoolExecutor

public static ScheduledExecutorService newScheduledThreadPool(

int corePoolSize, ThreadFactory threadFactory) {

return new ScheduledThreadPoolExecutor(corePoolSize, threadFactory);

}

public ScheduledThreadPoolExecutor(int corePoolSize,

ThreadFactory threadFactory) {

super(corePoolSize, Integer.MAX_VALUE,

DEFAULT_KEEPALIVE_MILLIS, MILLISECONDS,

new DelayedWorkQueue(), threadFactory);

}

核心线程数固定,非核心线程数没有限制,当非核心线程空闲会被立刻回收

适合执行定时任务和有固定周期的重复任务

参考最后使用示例

SingleThreadExecutor

public static ExecutorService newSingleThreadExecutor() {

return new FinalizableDelegatedExecutorService

(new ThreadPoolExecutor(1, 1,

0L, TimeUnit.MILLISECONDS,

new LinkedBlockingQueue()));

}

只有一个核心线程,所有的任务都会放到一个线程中去顺序执行

它统一了所有的外界任务到一个线程中,使得这些任务不需要处理线程间的同步问题。

使用示例

Runnable command = new Runnable() {

@Override

public void run() {

SystemClock.sleep(1000);

}

};

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);

fixedThreadPool.execute(command);

ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

cachedThreadPool.execute(command);

//2000ms后执行command

ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(3);

scheduledExecutorService.schedule(command, 2000, TimeUnit.MILLISECONDS);

//延迟10ms后执行,以后每隔1000ms执行一次command

scheduledExecutorService.scheduleAtFixedRate(command, 10, 1000, TimeUnit.MILLISECONDS);

ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();

singleThreadExecutor.execute(command);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值