Java Thread Waiting Methods and Notifications

I am learning OCJP, and now I am in the "Topic" chapter, I have some questions about waiting and notification methods. I think I understand what is happening here, but I just want to make sure I'm on the right track. I wrote this code as an example:

package threads;

public class Main {

    static Object lock = new Object();

    public static void main(String[] args) {
        new Main().new FirstThread().start();
        new Main().new SecondThread().start();
    }

    class FirstThread extends Thread {
        public void run() {
            synchronized (lock) {
                lock.notify();
                System.out.println("I've entered in FirstThread");
            }
        }
    }
    class SecondThread extends Thread {
        public void run() {
            synchronized (lock) {
                try {
                    lock.wait();
                    System.out.println("I'm in the second thread");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

In this example, the console output I've entered in FirstThread, because the first thread starts, the notify () method is called, then the second thread is started, the wait () method is called, and the line "I am in the second thread" is not printed.

The next scenario is that I change the position new Main().new FirstThread().start();and new Main().new SecondThread().start();the output

I've entered in FirstThread
I'm in the second thread

, wait(), , notify(), I've entered in FirstThread, I'm in the second thread .

, , ? start() , , ?.

, , - , , , , I've entered in FirstThread?

, JVM , Object.

+4
3

, 1 2, ( , , ).

, 2 , , ( 1) , , , (, ).

static lock Object: [First/Second]Thread Main, , .

, , new Main()... Main, lock.

+3

" , ? start() , , ?."

, sleep() , (unit-) . (, )

, , - ,

, , , , . ( ). , .

+3

, , :

synchronized (lock) {
    lock.notify();
    System.out.println("I've entered in FirstThread");
}

, :

synchronized (lock) {
    lock.wait();
    System.out.println("I'm in the second thread");
}

, lock.notify() , lock.wait() . , FirstThread notify() SecondThread wait(). wait() , notify() .

, (.. synchronized), wait() notify(). , , .

" " , :

 boolean firstThreadRan = false;

(a.k.a., "" ) :

 synchronized(lock) {
     firstThreadRan = true;
     lock.notify();
     ...
 }

(a.k.a., "" ) :

synchronized(lock) {
    while (! firstThreadRan) {
        lock.wait();
    }
    ...
}

while , , . .

0

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


All Articles