关于同步的问题:为什么这样写

Android 码拜 8年前 (2016-05-14) 816次浏览
private static final Object WAIT_SYNC = new Object();

synchronized (WAIT_SYNC) {
try {
WAIT_SYNC.wait();
} catch (InterruptedException ex) {
throw new KeyPromptingInterruptedException(ex);
}
}
目前是这块wait导致ANR,以下是本人adb抓到log
Reason: Input dispatching timed out (Waiting to send non-key event because the touched window has not finished processing certain input events that were delivered to it over 500.0ms ago.  Wait queue length: 8.  Wait queue head age: 14922.4ms.)
解决方案

40

首先这段等待的代码应该是被写到了主UI线程的处理流程中了,原因是线程调用WAIT_SYNC.wait()等待被唤醒,此时假如没有另外的线程调用WAIT_SYNC.notify()或WAIT_SYNC.notifyAll()的时候,主线程会一直等待,原因是忙等待而没有接收用户输入导致ANR
建议这段等待的代码不要放到ui线程,而要放到另外的工作线程中,然后等某些条件满足之后在另外的线程代码中去唤醒
参考:http://www.cnblogs.com/adamzuocy/archive/2010/03/08/1680851.html

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明关于同步的问题:为什么这样写
喜欢 (0)
[1034331897@qq.com]
分享 (0)