<> Chapter 11

2018-03-28  本文已影响0人  MZzF2HC

Android的线程和线程池

主线程和子线程

Android中的线程状态

除了传统的Thread外,还包含AsyncTaskHandlerThreadIntentService

1. AsyncTask

AsyncTask其实是封装了HandlerThread, 方便了我们的使用。

  1. AsynTask是一个抽象的泛型类,它提供了ParamsProgressResult这三个泛型参数,其中

    • Params表示参数类型,
    • Progress表示后台任务的执行进度的类型,
    • Result则表示后台返回结果
  2. AsyncTask提供了4个核心方法,含义如下

    • onPreExecute()在主线程中执行,在异步任务执行之前,此方法会被调用
    • doInBackground(Parms… params)在线程池中执行,此方法用于执行异步任务,params参数表示异步任务的输入参数
    • onProgressUpdate(Progress… values)在主线程中执行,当后台任务的执行进度发生改变时此方法会被调用
    • onPostExecute(Result result)在主线程中执行,在异步任务执行之后,此方法会被调用,其中result参数是后台任务的返回值.

    执行的顺序是onPreExecute()先执行,接着是doInBackground(),最后才是onPostExecute()
    PS:(有种情况是AsyncTask()还提供了onCancelled()方法,它同样在主线程中执行,当异步任务取消时,onCancelled()方法会被调用,这个时候onPostExecute()则不会被调用)

  3. AsyncTask具体有几点限制

    • AsyncTask第一次访问必须在主线程中加载,在android4.1及以上版本中已经被系统自动完成,和在android5.0源码中可以看出,在ActivityThreadmain()方法,它会调用AsyncTaskinit()方法,满足了在主线程中加载的条件。
    • AsyncTask的对象必须在主线程中创建
    • execute必须在UI线程调用(因为excute()方法中会调用onPreExecute())
    • 一个AsyncTask对象只能执行一次,即只能调用一次execute方法
    • 在Android1.6以前,AsyncTask是串行执行的,Android1.6的时候开始采用并行执行的方式,但是从Android3.0开始,为了避免AsyncTask所带来的兵法错误,AsyncTask又采用一个线程来串行执行任务。尽管如此,我们还是通过executeOnExecutor()方法来并发的执行任务。
2. HandlerThread

HandlerThread继承了Thread,在其run方法中通过Looper.prepare()方法来创建消息队列,并通过Looper.loop()来开启消息循环,这样在实际的使用中就允许在HandlerThread中创建Handler了。在不需要使用HandlerThread时,可以通过他的quit或者quitSafely方法来终止线程的执行

// HandlerThread run()方法
@Override
public void run() {
    mTid = Process.myTid();
    Looper.prepare();
    synchronized (this) {
        mLooper = Looper.myLooper();
        notifyAll();
    }
    Process.setThreadPriority(mPriority);
    onLooperPrepared();
    Looper.loop();
    mTid = -1;
}

//使用方法
HandlerThread handlerThread = new HandlerThread("MyHandler");
handlerThread.start();
Handler customHandler = new Handler(handlerThread.getLooper()){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
        // 处理Message
    }
};
3. IntentService
private final class ServiceHandler extends Handler {
    public ServiceHandler(Looper looper) {
        super(looper);
    }

    @Override
    public void handleMessage(Message msg) {
        onHandleIntent((Intent)msg.obj);
        stopSelf(msg.arg1);
    }
}

@Override
public void onCreate() {
    super.onCreate();
    HandlerThread thread = new HandlerThread("IntentService[" + mName + "]");
    thread.start();

    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper);
}

@Override
public void onStart(@Nullable Intent intent, int startId) {
    Message msg = mServiceHandler.obtainMessage();
    msg.arg1 = startId;
    msg.obj = intent;
    mServiceHandler.sendMessage(msg);
}

@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
    onStart(intent, startId);
    return mRedelivery ? START_REDELIVER_INTENT : START_NOT_STICKY;
}

Android中的线程池

使用线程池有以下好处:

Andorid中的线程池都是直接或者间接通过配置ThreadPoolExecutor来实现的

public ThreadPoolExecutor(int corePoolSize,
                        int maximumPoolSize,
                        long keepAliveTime,
                        TimeUnit unit,
                        BlockingQueue<Runnable> workQueue,
                        ThreadFactory threadFactory)

ThreadPoolExecutor执行任务时大致遵循如下规则:

  1. 如果线程池中的线程数量未达到核心线程的数量,那么会直接启动一个核心线程来执行任务。
  2. 如果线程池中的线程数量已经达到或者超过核心线程的数量,那么任务会被插入到任务队列中排队等待执行。
  3. 如果在步骤2中无法将任务插入到任务队列中,这往往是由于任务队列已满,这个时候如果线程数量未达到线程池规定的最大值,那么会立刻启动一个非核心线程来执行任务。
  4. 如果步骤3中线程数量已经达到线程池规定的最大值,那么就拒绝执行此任务,ThreadPoolExecutor会调用RejectedExecutionHandlerrejectedExecution方法来通知调用者。

AsyncTaskTHREAD_POOL_EXECUTOR线程池(执行任务的线程池)的配置:

线程池的分类:
public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(
        nThread, nThread, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>()
    );
}
public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(
        0L, Interger.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>()
    );
}
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

public ScheduledThreadPoolExecutor(int corePoolSize) {
    super(corePoolSize, Interger.MAX_VALUE, 0, NANOSECONDS, new DelayedWorkQueue());
}
public static ExecutorService newSingleThreadExecutor() {
    return new FinalizableDelegatedExecutorService(
        new ThreadPoolExecutor(1, 1, 0L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>())
    );
}
上一篇 下一篇

猜你喜欢

热点阅读