Android java.lang.IllegalMonitorStateException: object not locked by thread before wait()

后端 未结 4 786
夕颜
夕颜 2020-12-19 02:13

I define a global static object as a synchronization lock.

public static Object ConfirmationSynObj = new Object();

The following function i

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-19 02:32

    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)

    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.

    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.

提交回复
热议问题