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線程裏面就可以了。
以上是個人見解,如有不對,請不吝賜教,謝謝!!