首先明白:synchronized,是内置在jvm的内置锁
synchronized 的互斥访问机制。能修饰方法,代码块。
@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;
}
boolean wasInterrupted = false;
// If the thread has been started, wait until the looper has been created.
synchronized (this) {
while (isAlive() && mLooper == null) {
try {
wait();
} catch (InterruptedException e) {
wasInterrupted = true;
}
}
}
上面的两段代码可知 HandlerThread 是互斥的。
其中,getlooper()如果先触发,进入synchronized代码段后,回用while循环判断,进行wait()等待。wait()的作用是等待别人使用锁----会让线程挂起,释放锁,然后run()方法执行完里的 notifyAll() 通知挂起的线程---wait结束
1.为什么用wait,不用sleeo。
wait 是挂起,释放对象锁。
sleep是不会释放对象的。
2.为什么用notifyAll() ,不用notify()
notifyAll()对所有线程通知。实际情况,不知道有多少个地方都在wait。
notifyAll()和wait不是一一对应的。wait会立刻交出锁,立刻执行,但是notifyALL通知 wait等到锁锁里的内容完成。所以上面代码里的notifyAll 和 mLooper = Looper.myLooper(); 交换顺序没有影响
3.为什么用while不用if?
实际场景中,使用if只有一次。必须保证m looper非空