HandlerThread原理和使用

HandlerThread作用 为方便我们在安卓线程间通信,像在主线程一样使用子线程,不用我们自己手动的去调用Looper.prepare()和Looper.loop()
HandlerThread原理 【HandlerThread原理和使用】他是继承自Thread的,主要实现在run方法

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

在线程run的时候会为这个线程创建Looper,我们在使用的时候可以获取Looper,然后把Looper作为参数创建Handler,就可以实现线程间通信了
注意:
HandlerThread在使用后如果退出页面需要调用quit()或者quitSafe()方法,防止内存溢出,他们两个的区别是一个是清除队列中所有Message,一个是清除时间大于调用时间的Message
HandlerThread的使用
public class MyHandlerThread extends Thread{private Handler mHanlder; public static class MyHandler extends Handler{public MyHandler(Looper looper){ super(looper); }@Override public void handleMessage(Message msg) { super.handleMessage(msg); LogUtils.log("handleMessage = " + Thread.currentThread().getName()); } }public MyHandlerThread(){ init(); }private void init() { LogUtils.log("init = " + Thread.currentThread().getName()); HandlerThread handlerThread = new HandlerThread("MyHandlerThread"); handlerThread.start(); Looper looper = handlerThread.getLooper(); mHanlder = new MyHandler(looper); }@Override public void run() { super.run(); LogUtils.log("run = " + Thread.currentThread().getName()); mHanlder.sendEmptyMessage(1); }public void startThread(){ Executors.newSingleThreadExecutor().execute(new Runnable() { @Override public void run() { LogUtils.log("Runnable = " + Thread.currentThread().getName()); mHanlder.sendEmptyMessage(1); } }); } }

调用代码
public class MainActivity extends AppCompatActivity { @OnClick(R.id.tv_hello_world) void helloworld(){ testHandlerThread(); }public void testHandlerThread(){ myHandlerThread.startThread(); }private MyHandlerThread myHandlerThread; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); myHandlerThread = new MyHandlerThread(); myHandlerThread.start(); } }

输出

HandlerThread原理和使用
文章图片
image.png
使用HandlerThread获取Looper时要注意要先吧HandlerThread start后才能获取Looper
1,创建是在主线程
2,在子线程中启动
3,在子线程中发消息
4,最后在通过HandlerThread创建出来的线程中处理

    推荐阅读