m0_47891564
maohaocheng.
2021-01-21 23:36

有大佬可以告诉我下面代码为啥debug跟run结果不一致吗。

  • spring
  • java
  • jar
  • intellij-idea
  • java-ee
public class Main {
    public static void main(String[] args) throws InterruptedException {
        Test test = new Test();
        Thread thread1 = new Thread(() -> {
            try {
                System.out.println(test.change());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        Thread thread2 = new Thread(() -> {
            try {
                System.out.println(test.change());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread1.start();
        TimeUnit.MILLISECONDS.sleep(8);
        thread2.start();
    }
}
public class Test {
    private volatile int a = 0;
    public int change() throws InterruptedException {
        while (a == 0){
            TimeUnit.MILLISECONDS.sleep(10);
            a++;

        }
        return a;
    }

}
  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

11条回答