简单描述下代码:
static 变量 i
线程 1:尝试把 i 设为 1
线程 2:尝试把 i 设为 2 ,如果 i 为 1 ,print i
不断运行线程 1 和 2
public class Main {
// static 变量 i
static volatile Integer i = 0;
public static void main(String[] args) throws Exception {
// 线程 1
Thread thread1 = new Thread(()->{
synchronized(i) {
try {
i = 1;
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
// 线程 2
Thread thread2 = new Thread(()->{
synchronized (i) {
try {
i = 2;
Thread.sleep(100);
if (i == 1) {
System.out.println("1"); // 实际运行结果为 1
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
// 不断运行线程 1 和 2
while (true) {
new Thread(thread1).start();
new Thread(thread2).start();
}
}
}
为什么运行的结果是 1
还请各位大佬不吝赐教(抱拳),
谢谢各位大哥