先看一个使用HandlerThread的例子:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); HandlerThread thread = new HandlerThread("handler_thread");//1 创建一个HandlerThread thread.start(); final Handler handler = new Handler(thread.getLooper()) {//2 创建Handler的时候,使用HandlerThread的Looper @Override public void handleMessage(Message msg) { Log.i(TAG, msg.what+ ","+ Thread.currentThread().getName()); //4 在子线程中处理消息 super.handleMessage(msg); } }; new Thread(new Runnable() { @Override public void run() { for (int j = 0; j < 5; j++) { Message msg = Message.obtain(); msg.what = j; handler.sendMessage(msg); //3 向handler发送消息 try{Thread.sleep(1000);}catch(Exception e){} } } }).start(); }
我们看下ThreadHandler的源码:
public class HandlerThread extends Thread { //继承了Thread ...... Looper mLooper; //有一个Looper的成员变量 ...... @Override public void run() { mTid = Process.myTid(); Looper.prepare(); //在子线程中创建Looper synchronized (this) { mLooper = Looper.myLooper(); notifyAll(); //唤醒getLooper时等待的线程 } Process.setThreadPriority(mPriority); onLooperPrepared(); Looper.loop(); //开始消息循环 mTid = -1; } public Looper getLooper() { if (!isAlive()) { return null; } // If the thread has been started, wait until the looper has been created. synchronized (this) { while (isAlive() && mLooper == null) { //这里保证Looper已经初始化完成 try { wait(); } catch (InterruptedException e) { } } } return mLooper; } }
原文地址:http://blog.csdn.net/goldenfish1919/article/details/45690501