HandlerThread源码分析
public class HandlerThread extends Thread {
int mPriority;
int mTid = -
1;
Looper mLooper;
public HandlerThread(String name) {
super(name);
mPriority = Process.THREAD_PRIORITY_DEFAULT;
}
public HandlerThread(String name,
int priority) {
super(name);
mPriority = priority;
}
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;
}
public Looper
getLooper() {
if (!isAlive()) {
return null;
}
synchronized (
this) {
while (isAlive() && mLooper ==
null) {
try {
wait();
}
catch (InterruptedException e) {
}
}
}
return mLooper;
}
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;
}
public int getThreadId() {
return mTid;
}
}
Looper#quit相关源码
public void quit() {
mQueue.quit(
false);
}
public void quitSafely() {
mQueue.quit(
true);
}
void quit(
boolean safe) {
if (!mQuitAllowed) {
throw new IllegalStateException(
"Main thread not allowed to quit.");
}
synchronized (
this) {
if (mQuitting) {
return;
}
mQuitting =
true;
if (safe) {
removeAllFutureMessagesLocked();
}
else {
removeAllMessagesLocked();
}
nativeWake(mPtr);
}
}
private void removeAllMessagesLocked() {
Message p = mMessages;
while (p !=
null) {
Message n = p.next;
p.recycleUnchecked();
p = n;
}
mMessages =
null;
}
private void removeAllFutureMessagesLocked() {
final long now = SystemClock.uptimeMillis();
Message p = mMessages;
if (p !=
null) {
if (p.when > now) {
removeAllMessagesLocked();
}
else {
Message n;
for (;;) {
n = p.next;
if (n ==
null) {
return;
}
if (n.when > now) {
break;
}
p = n;
}
p.next =
null;
do {
p = n;
n = p.next;
p.recycleUnchecked();
}
while (n !=
null);
}
}
}
转载请注明原文地址: https://ju.6miu.com/read-660102.html