在一个线程里面调用另一个线程的sleep方法

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);
    }
}

我的想象是:主线程直接打印444 和0,而不必等待2s.
可是现实就是主线程等待了2s,而t2线程没有等待。
直接看sleep源码

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

原来是个静态方法啊。所以在主线程里面调用t2.sleep其实相当于sleep,所以哪个线程调用sleep,哪个线程就睡眠。
所以上面代码可以把t2.sleep放在t2线程里面就可以了。

以上是个人见解,如有不对,请不吝赐教,谢谢!!

猜你喜欢

转载自blog.csdn.net/qq_43179428/article/details/106801280