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; } }
跟debug还是直接run没关系吧,你这代码每次结果本来就可能会不一样
不会呀,run会遵循volatile,改了a后第二个线程会在1的基础上加,debug则是在0的基础上,或者是直接返回a了
你这并不能保证线程2 到的时候 线程1 已经把a值给改了呀,你可以多点点 run的时候也会有1,1的情况的。
你这sleep的时间太短了,跟debug没啥关系的
a++ 本身就是有问题的,他是不能保证事务的吧, 实际的a++ 操作 分为 a + 1 和 a= a+1
我想的是我用两个延时,确保1在2前面,我想看到的是效果是,1改了a后,2还会不会while判断,呈现出来的是run不会,而debug会
加长延时时间也是一样的
你想达到这个效果,a++ 应该在
TimeUnit.MILLISECONDS.sleep(10);前面
你重新运行几次看一下结果吧,感觉应该不是debug和run的问题原因。
debug的时候不雅打断点
多线程运行你要给他们同时都打上断点没?