安卓java.lang.IllegalMonitorStateException:等待对象之前没有锁定的线程()线程、对象、java、lang

2023-09-06 09:37:32 作者:如果冷请热吻

我定义一个全局的静态对象作为同步锁。

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;
            }
        }

有谁知道如何锁定对象或函数,以prevent并发?

Does anyone know how to lock an object or a function in order to prevent the concurrency?

推荐答案

一个常见的​​替代品 / 通知 CountDownLatch 。 (摘自的java.util.concurrent 很好,但工作种类的旗语逆 - 看到汤姆回答)

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;
    }
}

不过,code,你写的有可以简化为

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.

如果您尝试这样做的UI线程以外的HTTP请求,因为你得到的 NetworkOnMainThreadExcpeption ,你必须以不同的做到这一点。虽然Android将无法检测到您的code因为很长一段时间阻止code它仍然是。用一个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.