本文参考StackOverflow: https://stackoverflow.com/questions/6964011/handler-vs-asynctask-vs-thread

1. Thread

线程,就是最基本的定义。一个程序会有多个线程来执行不同的Task。Handler和AsyncTask都属于Thread。在Handler和AsyncTask的底层都是由Thread实现的。

2. AsyncTask

先附上官方的定义:

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers

翻译一下:

AsyncTask为UI线程(即Main Event Thread)的使用提供了一个简单的方式。这个类允许Background(后台)任务简单的在不使用thread和handler的情况下对UI线程进行操作。

接触过AsyncTask的朋友对其都不陌生。其中有onPreExecute(), doInBackground(), onPostExecute(),运行我们在不同的阶段对UI和后台线程进行操作。同时也确保了我们可以在三个时间段连续做不同的事情,不需要自己使用thread和handler做线程的schedule。

其中onPreExecute()和onPostExecute()是被Main Event Thread(即UI thread)调用。所以可以直接与UI thread交流。

Using Scenario:

  1. 如果你需要在后台执行一些有顺序的Code
  2. 需要与UI Thread 进行交流

3. Handler

官方定义:

Handler allows you to send and process Message and Runnable objects associated with a thread’s MessageQueue

翻译一下:

Handler允许你发送Message和Runnable Object到一个线程的MessageQueue

用过Handler的都知道Handler里面需要Post Ruannable对象。这个Runnable对象其实就是发送到自创线程的MessageQueue队列中。

Handler就像是一座桥连接了UI thread和自创Thread。

Using Scenario:

  1. 需要在后台执行Code
  2. 需要与UI Thread进行交楼

4. Conclusion

所以Thread, Handler和AsyncTask的复杂关系应该为:

Thread < Handler < AsyncTask

Thread最普通,就是创建一个线程而已。

Handler比Thread功能更多,可以连接两个Thread

AsyncTask是功能更复杂的thread,可以连接两个thread还可以让thread中code按顺序执行

AsyncTask和Handler和UI Thread的交流是不同的方式。Handler是建立通道,而AsyncTask是UI Thread直接call AsyncTask里面的onPreExecute(), onProgressUpdate()和onPostExecute()。这导致一些区别,比如说我们不能加载Network Thread在Handler里面,但是我们可以加载NewtWork Thread在AsyncTask中,因为NetworkThread不可以在MainThread上Run,否则会抛出NetworkOnMainThreadException。官方介绍和地址如下:

NetworkOnMainThreadException

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it’s heavily discouraged. See the document Designing for Responsiveness.

Also see StrictMode StrictMode Link.