Java synchronization games: synchronized && wait && notify

I come from the world .NETand, unfortunately, look at the Java source with eyes .NET.

The following code from Android Apps (although not for Android):

    private class Worker implements Runnable {
        private final Object mLock = new Object();
        private Looper mLooper;

        Worker(String name) {
            Thread t = new Thread(null, this, name);
            t.start();
            synchronized (mLock) {
                while (mLooper == null) {
                    try {
                        mLock.wait();
                    } catch (InterruptedException ex) {
                    }
                }
            }
        }

        public Looper getLooper() {
            return mLooper;
        }

        public void run() {
            synchronized (mLock) {
                Looper.prepare();
                mLooper = Looper.myLooper();
                mLock.notifyAll();
            }
            Looper.loop();
        }

        public void quit() {
            mLooper.quit();
        }
    }

I don’t quite understand how it works synchronized. At first I thought that the synchronized locking object was mLock, but if after the t.start()constructor thread first enters the synchronization block, it blocks it at mLock.wait()and implicitly blocks the "t" thread, blocking it from entering the synchronized block.

This is obviously wrong, because my phone rings as expected :)

, " " ( = > ), ...

... , mLock.wait() mLock mLock .

, , .

+3
4

javadoc Object.wait(). "" , , {}. Object.notify().

notify(), wait(), , - () . , . .

+8

synchronized . wait() ( notify ()).

+1

. wait(), , , notify notifyAll. , , , .

, "" (.. ) Worker . private, , , .

+1
source

Let me explain:

The constructor starts a new thread, which the run () method will execute. This new thread will receive a new Looper object, save it in the mLooper field, and start the Looper loop. In between, it will notify () the first thread that was installed in the mLooper file.

Therefore, the first thread will only return from the constructor after mLooper is installed, which means that Looper.loop () processing in the second thread will be started soon / already started.

0
source

Source: https://habr.com/ru/post/1725957/


All Articles