HandlerThread是什么?
点开类楸一眼,这货是这样介绍自己的:
* Handy class for starting a new thread that has a looper. The looper can then be
* used to create handler classes. Note that start() must still be called.
大意是说它是用来启动具有一个内部循环的新线程的一个便利类。
内部循环?同时名称又有Handler又有Thread,看过我这篇文章的同学估计猜到了,这货估计是Handler与Thread的亲儿子无疑了
往期目录:
Android/java 多线程(一)-Thread的使用以及源码分析
Android/java 多线程(二)-Thread的好兄弟Handler
我在上篇文章介绍Handler的时候举了一个例子,在子线程中使用Handler:
class MyThread extends Thread {
@Override
public void run() {
Looper.prepare();
@SuppressLint("HandlerLeak")
Handler mHandler = new Handler(){
@Override
public void handleMessage(Message msg) {
//处理逻辑
l(Thread.currentThread().getName());
}
};
Message message = mHandler.obtainMessage(1);
mHandler.sendMessage(message);
Looper.loop();
}
}
是不是显得巨麻烦,而且巨丑,HandlerThread
就是为了防止我们写出如此丑陋的代码而生的,它的本质原理其实也就是以上那几行代码。不信?,我们来瞅瞅
HandlerThread源码
public class HandlerThread extends Thread {
int mPriority; //线程优先级
int mTid = -1;
Looper mLooper;
private @Nullable Handler mHandler;
//指定线程的名称,默认线程优先级为DEFAULT,也是最低级的
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
//指定线程的名称,同时指定线程的优先级
public HandlerThread(String name, int priority) {
super(name);
mPriority = priority;
}
//这里主要处理一些数据的初始化啊一些子线程的逻辑操作啥的,在run()方法中回调
protected void onLooperPrepared() {
}
//熟悉的run()方法
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare(); //创建Looper()
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll(); //到这里Looper已经创建完毕,唤醒阻塞的线程
}
//设置线程优先级
Process.setThreadPriority(mPriority);
onLooperPrepared(); //执行onLooperPrepared()方法
Looper.loop(); //开启循环
mTid = -1;
}
/**
* This method returns the Looper associated with this thread. If this thread not been started
* or for any reason isAlive() returns false, this method will return null. If this thread
* has been started, this method will block until the looper has been initialized.
* @return The looper.
*/
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) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
return mLooper;
}
/**
* @return a shared {@link Handler} associated with this thread
* @hide
*/
@NonNull
public Handler getThreadHandler() {
if (mHandler == null) {
mHandler = new Handler(getLooper());
}
return mHandler;
}
//非安全的结束循环
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}
////安全的结束循环
public boolean quitSafely() {
Looper looper = getLooper();
if (looper != null) {
looper.quitSafely();
return true;
}
return false;
}
/**
* Returns the identifier of this thread. See Process.myTid().
*/
public int getThreadId() {
return mTid;
}
}
结合源码,这货其实也就是在run()中开启了Looper循环,并提供了一个onLooperPrepared ()
方法供我们使用,做一些初始化的操作。
需要注意的是quit()
方法和quitSafely()
的区别,quit()
是立即停止Looper循环,此时可能有消息未处理就GG了,所以说它的不安全的,而quitSafely()
是等待消息处理完毕后才停止Looper循环,所以说它是安全的,另外可以看到它指定线程优先级是使用的Process.setThreadPriority(mPriority)
方法,所有它的可选值是从Process()
里面获取
HandlerThread的使用场景
HandlerThread的优点
HandlerThread里面的本质实际上是子线程消息轮询机制,我们能够从中获取到一个在子线程中轮询的Looper,如果设置给Handler,那么这个Handler就能在子线程中处理消息。所以它特别适合处理大量需要排队等待或需要重复操作的又耗时的逻辑,它既能够方便的通知主线程更新UI,内部又能方便的做线程的队列处理,所以它的使用还是比较广泛滴。
举个栗子
假设有这么个需求:需要批量下载文件,一次只能下载一个,下载完毕后自动下载下一个,或者这个下载失败或暂停自动下载下一个(是不是有点像某雷的下载场景),伪实现如下:
/**
* Created by hj on 2018/12/21.
* 说明:模拟线程下载
*/
public class DownloadHandlerThread extends HandlerThread implements Handler.Callback {
private Handler workHandler; //处理下载逻辑的Handler
private Handler uiHandler; //处理UI刷新的Handler
public final static int READY = 0X110;
public final static int STAR = 0X111;
public final static int STOP = 0X112;
public final static int ERROR = 0X113;
private int max;
private int index;
public DownloadHandlerThread() {
super("download-thread");
}
@Override
protected void onLooperPrepared() {
//初始化
workHandler = new Handler(getLooper(), this);
if (uiHandler == null) {
throw new NullPointerException("uiHandler is not null");
}
uiHandler.sendEmptyMessage(READY); //通知主线程Looper已经准备完毕,可以开始下载了
}
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case STAR: //开始下载
index++; //记录当前下载到了第几个
String url = msg.getData().getString("url");
Log.i("HJ", "准备下载:" + url);
try {
sleep(2000); //模拟下载
if (index == 2) { //下载到第二个的时候模拟下载失败
Log.i("HJ", "下载出错:" + url);
setErrorMessage(url);
Log.i("HJ", "开始下载下一个地址");
} else {
Log.i("HJ", "当前地址下载完成:" + url);
}
} catch (InterruptedException e) {
setErrorMessage(url);
e.printStackTrace();
}
if (index == max) { //全部下载完毕
workHandler.sendEmptyMessage(STOP);
}
break;
case STOP: //全部下载完成
//退出Looper循环
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
quitSafely();
} else {
quit();
}
Log.i("HJ", "全部下载完成");
break;
}
return false;
}
//发送下载错误消息到主线程用于刷新UI
private void setErrorMessage(String url) {
Message errorMsg = new Message();
errorMsg.what = ERROR;
Bundle bundle = new Bundle();
bundle.putString("errorUrl", url);
errorMsg.setData(bundle);
uiHandler.sendMessage(errorMsg);
}
public void setUiHandler(Handler uiHandler) {
this.uiHandler = uiHandler;
}
public Handler getWorkHandler() {
return workHandler;
}
public void setMax(int max) {
this.max = max;
}
}
在Activity中使用:
public class MainActivity extends AppCompatActivity {
private Handler uiHandler;
//模拟数据源
private String[] urls = new String[]{
"url-1", "url-2", "url-3", "url-4", "url-5"
};
private DownloadHandlerThread mThread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initUiHandler();
initDownLoad();
}
@SuppressLint("HandlerLeak")
private void initUiHandler() {
uiHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DownloadHandlerThread.READY: //获取到workHandler已经初始化完毕,可以进行下载任务了
Handler workHandler = mThread.getWorkHandler();
mThread.setMax(urls.length);
for (String url : urls) { //循环将Message加入MessageQueue消息池中
Message message = new Message();
message.what = DownloadHandlerThread.STAR;
Bundle bundle = new Bundle();
bundle.putString("url", url);
message.setData(bundle);
workHandler.sendMessage(message);
}
break;
case DownloadHandlerThread.ERROR: //处理下载失败UI逻辑
String url = msg.getData().getString("errorUrl");
showShortToast("下载失败链接:" + url);
Log.i("HJ","展示下载失败UI>>>>>>>>");
break;
}
}
};
}
private void showShortToast(String string) {
Toast.makeText(this, string, Toast.LENGTH_SHORT).show();
}
private void initDownLoad() {
mThread = new DownloadHandlerThread();
mThread.setUiHandler(uiHandler);
mThread.start();
}
}
运行结果如下:
2018-12-21 11:51:02.775 2390-2432/com.zj.example.customview.funnel I/HJ: 准备下载:url-1
2018-12-21 11:51:04.775 2390-2432/com.zj.example.customview.funnel I/HJ: 当前地址下载完成:url-1
2018-12-21 11:51:04.775 2390-2432/com.zj.example.customview.funnel I/HJ: 准备下载:url-2
2018-12-21 11:51:06.777 2390-2432/com.zj.example.customview.funnel I/HJ: 下载出错:url-2
2018-12-21 11:51:06.777 2390-2432/com.zj.example.customview.funnel I/HJ: 开始下载下一个地址
2018-12-21 11:51:06.778 2390-2432/com.zj.example.customview.funnel I/HJ: 准备下载:url-3
2018-12-21 11:51:06.779 2390-2390/com.zj.example.customview.funnel I/HJ: 展示下载失败UI>>>>>>>>
2018-12-21 11:51:08.778 2390-2432/com.zj.example.customview.funnel I/HJ: 当前地址下载完成:url-3
2018-12-21 11:51:08.778 2390-2432/com.zj.example.customview.funnel I/HJ: 准备下载:url-4
2018-12-21 11:51:10.779 2390-2432/com.zj.example.customview.funnel I/HJ: 当前地址下载完成:url-4
2018-12-21 11:51:10.779 2390-2432/com.zj.example.customview.funnel I/HJ: 准备下载:url-5
2018-12-21 11:51:12.783 2390-2432/com.zj.example.customview.funnel I/HJ: 当前地址下载完成:url-5
2018-12-21 11:51:12.783 2390-2432/com.zj.example.customview.funnel I/HJ: 全部下载完成
可以看到DownloadHandlerThread
主要承载的功能如下:
- 初始化一个子线程Handler用于处理子线程的消息通信
- 执行下载任务以及与主线程的ui通信
这样的处理方式极大的方便了ui线程与子线程的通讯,只需要用不同的handler发送消息即可,来再多的handler都不怕。而且这只需要开启一个线程,极大的节省了内存空间,而且能让线程任务有序进行,方便管理。
建议将以上代码复制过去跑一跑,调试一下,这样能更快的理解HandlerThread的通信以及它的便捷通信机制。