-
正常情况下使用线程我们都是直接new Thread.start来开启,但是这种方式是执行完run 方法后线程结束了,当我们有多个线程的时候意味着我们需要开启多个线程去执行,这样是很耗费CPU资源的。
-
HandlerThread解决了这个问题,它是一个继承于Thread的类,内部的run方法实现了一套looper机制,可以不让这个子线程结束。内部的looper里面有一个死循环,如果有消息就把任务发送到子线程中处理,没有则挂起等待新的消息到来。
使用场景
如果你有多个耗时操作需要开启多个子线程操作的话,你可以考虑使用它,它的好处是一个线程可以持续的执行多个任务队列,节省资源方便维护。 坏处是不适合那些需要马上响应的耗时操作,比如网络请求,如果网络请求走队列的话,任务一多请求就会一直堵塞等待执行。
注意事项
Handler如果要在子线程中创建必须调用 Looper.prepare();初始化一个looper,Handler会在构造检查looper没有会抛出异常,但是在主线程中就不需要,因为主线程中默认已经包含了一个MainLooper对象。
检查Looper的代码
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
使用起来
HandlerThread handlerThread = new HandlerThread("mainhander");
handlerThread.start();
Handler handler = new Handler(handlerThread.myLooper()) {
@Override
public void dispatchMessage(Message msg) {
LogU.Log("pId=" + Process.myTid());
}
};
handler.sendEmptyMessage(1);
这个时候handlerThread子线程已经具备了队列的功能,而且线程是一直在的,内部的Looper一直处理挂起状态等带新的消息到来。
结束handlerThread线程
handlerThread自带了二个结束线程队列的方法, 一个是线程安全一个线程不安全,当我们不需要在用这个子线程的时候需要及时的结束它,免的占用资源。
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;
}
Looper初始化特点
1.子线程的Looper就变成子线程回调
2.主线程的Looper就变成主线程回调
/**
* 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.
*/
public class HandlerThread extends Thread {
int mPriority;
int mTid = -1;
Looper mLooper;
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
/**
* Constructs a HandlerThread.
* @param name
* @param priority The priority to run the thread at. The value supplied must be from
* {@link android.os.Process} and not from java.lang.Thread.
*/
public HandlerThread(String name, int priority) {
super(name);
mPriority = priority;
}
/**
* Call back method that can be explicitly overridden if needed to execute some
* setup before Looper loops.
*/
protected void onLooperPrepared() {
}
@Override
public void run() {
mTid = Process.myTid();
Looper.prepare();
synchronized (this) {
mLooper = Looper.myLooper();
notifyAll();
}
Process.setThreadPriority(mPriority);
onLooperPrepared();
Looper.loop();
mTid = -1;
}
/**
* This method returns the Looper associated with this thread. If this thread not been started
* or for any reason is 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;
}
/**
* Quits the handler thread's looper.
* <p>
* Causes the handler thread's looper to terminate without processing any
* more messages in the message queue.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p class="note">
* Using this method may be unsafe because some messages may not be delivered
* before the looper terminates. Consider using {@link #quitSafely} instead to ensure
* that all pending work is completed in an orderly manner.
* </p>
*
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*
* @see #quitSafely
*/
public boolean quit() {
Looper looper = getLooper();
if (looper != null) {
looper.quit();
return true;
}
return false;
}
/**
* Quits the handler thread's looper safely.
* <p>
* Causes the handler thread's looper to terminate as soon as all remaining messages
* in the message queue that are already due to be delivered have been handled.
* Pending delayed messages with due times in the future will not be delivered.
* </p><p>
* Any attempt to post messages to the queue after the looper is asked to quit will fail.
* For example, the {@link Handler#sendMessage(Message)} method will return false.
* </p><p>
* If the thread has not been started or has finished (that is if
* {@link #getLooper} returns null), then false is returned.
* Otherwise the looper is asked to quit and true is returned.
* </p>
*
* @return True if the looper looper has been asked to quit or false if the
* thread had not yet started running.
*/
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;
}
}
网友评论