Strange java wait / notify behavior

I found the weird behavior of java concurrency. See the following code below:

    public class Test {
        static CountDownLatch latch = new CountDownLatch (1);
        public static void main (String [] args) throws UnsupportedEncodingException, InterruptedException {
            final Thread t = new MyThread ();
            t.start ();
            synchronized (t) {
                latch.countDown ();
                System.out.println ("got to sleep");
                t.wait ();
                System.out.println ("wake up");
            }
        }

        static class MyThread extends Thread {
            @Override
            public void run () {
                try {
                    latch.await ();
                } catch (InterruptedException e) {
                    e.printStackTrace ();
                }
                synchronized (this) {
                    System.out.println ("inside run");
    // notifyAll ();
                }
            }
        }
    }

From my point of view, this code should be hung up and wait forever, but the code ends without any problems with the following in the console:

got to sleep
inside run
wake up

I tried to find some information about the notification of locks if the thread died, but it was missing. Also, I did not find any information in the java specification.

But if I tried to block some other object (and not a thread object), it worked fine, as I expected.

+4
source share
2 answers

, Thread. Thread wait/notify/notifyAll , - Thread, Thread . , , this.notifyAll().

Thread.join:

this.wait , this.isAlive. , this.notifyAll . , wait, notify notifyAll Thread .

, , . , concurrency , , . ( wait/notify ..), , . - :

public class Foo {
    private final Object lock = new Object();

    ... code which uses synchronized(lock) ...
}
+6

Jon Skeet, Thread, :

public class Test {
    static CountDownLatch latch = new CountDownLatch(1);
    static final Object sync = new Object();

    public static void main(String[] args) throws UnsupportedEncodingException, InterruptedException {
        final Thread t = new MyThread();
        t.start();
        synchronized (sync) {
            latch.countDown();
            System.out.println("got to sleep");
            sync.wait();
            System.out.println("wake up");
        }
    }
}

static class MyThread extends Thread {
    @Override
    public void run() {
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        synchronized (sync) {
            System.out.println("inside run");
            //sync.notifyAll();
        }
    }
}

, sync.notifyAll();

0

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


All Articles