线程中的synchronized使用

 

private static class ListenerHandlerThread implements Runnable {

 

private Looper looper;

 

private byte[] listenerKey = new byte[0];

 

public ListenerHandlerThread() {

new Thread(this).start();

synchronized (listenerKey) {

while (looper == null) {  //注意while必须放synronized里面,不然会出错

try {

listenerKey.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

 

public Looper getLooper() {

return looper;

}

 

@Override

public void run() {

Looper.prepare();

looper = Looper.myLooper();

synchronized (listenerKey) {

listenerKey.notifyAll();

}

Looper.loop();

}

 

}

你可能感兴趣的:(thread)