有时候为了将异步回调改为同步操作,会用到wait
和notify
,如果notify发生在wait之后,将出现“锁死”的现象
Executors.getInstance().background(new Runnable() {
public void run() {
getPermissionRequestDelegate().requestPermissions(permissions, new PermissionResultReceiver() {
public void onGranted(String[] permissions) {
notifySignal();
}
public void onDenied(String[] permissions) {
notifySignal();
}
public void onCanceled() {
notifySignal();
}
});
}
});
waitSignal();
如果background内的方法先于waitSignal执行,就会出现“锁死”
简答的解决办法就是判断是否已经调用了noitfy方法
final int[] invoked = new int[]{0};
Executors.getInstance().background(new Runnable() {
public void run() {
getPermissionRequestDelegate().requestPermissions(permissions, new PermissionResultReceiver() {
public void onGranted(String[] permissions) {
invoked[0] = 1;
notifySignal();
}
public void onDenied(String[] permissions) {
invoked[0] = 1;
notifySignal();
}
public void onCanceled() {
invoked[0] = 1;
notifySignal();
}
});
}
});
synchronized (signal) {
if (invoked[0] == 0) {
waitSignal();
}
}