How does multithreading ensure that the current thread executes obj.notify () before another thread executes obj.wait ()?

if a thread"s wait executes before notify, then the program dies. How can we solve this problem?

public class AaaTest {
    public static void main(String[] args) throws InterruptedException {
        Object obj=new Object();
        Ttt ttt=new Ttt(obj);
        ttt.start();
        synchronized(obj){
            obj.wait();
        }
        System.out.println("wait");
    }
    static class Ttt extends Thread{
        Object obj;
        Ttt(Object obj){
            this.obj=obj;
        }
        public void run() {
            synchronized(obj){
                    obj.notify();
            }
        }
    }
}

is this 100% guaranteed that obj.wait (); will be executed before obj.notify ();?

Feb.28,2021

of course not!
because it is uncertain which thread enters the Synchronize block first.

The

main method can be changed as follows:

  

No. The main thread is still a ttt thread. The one that first enters the synchronization block synchronized (obj) {} cannot be guaranteed. The positive solution upstairs

Menu