Android java.lang.IllegalMonitorStateException:对象未在等待()之前被线程锁定
我将一个全局静态对象定义为同步锁.
I define a global static object as a synchronization lock.
public static Object ConfirmationSynObj = new Object();
下面的函数是我写的,但是它抛出了一个 IllegalMonitorStateException.
The following function is what I wrote, but it throw a IllegalMonitorStateException.
synchronized (Config.ConfirmationSynObj) {
new Thread(new Runnable() {
@Override
public void run() {
//this is a http request
appSignInfo = getAPKSignature(context, pkinfo.packageName);
Config.ConfirmationSynObj.notify();
}
}).start();
try {
Config.ConfirmationSynObj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (appSignInfo == null) {
return ret;
}
}
有谁知道如何锁定对象或函数以防止并发?
Does anyone know how to lock an object or a function in order to prevent the concurrency?
推荐答案
wait
/notify
的常见替代品是 CountDownLatch
.(也来自 java.util.concurrent
,但工作方式与 Semaphore
是相反的 - 请参阅 Tom 的回答)
A common replacement for wait
/notify
is CountDownLatch
. (From java.util.concurrent
as well but working kind of inverse of Semaphore
- see answer by Tom)
您将其初始化为所需的步数,已完成倒计时的线程和其他一些地方等待倒计时达到 0.
You initialize it to the amount of steps required, threads that have finished count down and some other place waits for the countdown to reach 0.
void doFoo() {
final CountDownLatch latch = new CountDownLatch(1);
new Thread(new Runnable() {
@Override
public void run() {
//this is a http request
appSignInfo = getAPKSignature(context, pkinfo.packageName);
latch.countDown();
}
}).start();
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (appSignInfo == null) {
return ret;
}
}
但是你在那里写的代码可以简化为
But the code you wrote there can be simplified to
void doFoo() {
return getAPKSignature(context, pkinfo.packageName);
}
您启动第二个线程来做某事,而您在那段时间所做的就是等待.如果在该任务运行时无事可做,请不要创建额外的线程.结果是一样的.
You start a second thread to do something and all you do in that time is to wait. If there is nothing to do while that task is running don't create an extra thread. The result is the same.
如果您因为得到 NetworkOnMainThreadExcpeption
而尝试在 UI 线程之外执行 HTTP 请求,则必须以不同的方式执行.虽然 Android 不会像长时间阻塞代码那样检测到您的代码,但它仍然是.以 AsyncTask 为例.
If you try to do a HTTP request outside of the UI thread because you get that NetworkOnMainThreadExcpeption
, you have to do it differently. While Android won't detect your code as long time blocking code it still is. Use an AsyncTask for example.
相关文章