Call the sleep method of another thread in one thread

import static java.lang.Thread.sleep;
public class send {
    
    
    static  int x;
    public static void  main(String[] agrs) throws InterruptedException {
    
    
        Thread t2 = new Thread(() -> {
    
    
            x=10;
        }, "t2");
        t2.start();
        t2.sleep(2000);
        System.out.println(444);
        System.out.println(x);
    }
}

My imagination is: the main thread directly prints 444 and 0 without waiting for 2s.
But the reality is that the main thread waits for 2s, while the t2 thread does not wait.
Look directly at the sleep source code

 public static native void sleep(long millis) throws InterruptedException;

It turned out to be a static method. So calling in the main thread is t2.sleepactually equivalent sleep, so which thread calls sleep, which thread sleeps.
So the above code can be put t2.sleepin the t2 thread.

The above is my personal opinion, if there is something wrong, please feel free to enlighten me, thank you!!

Guess you like

Origin blog.csdn.net/qq_43179428/article/details/106801280