在Java中,volatile关键字错误
在Java中,volatile关键字错误
这个问题已经有答案了:
我正在尝试编写一个简单的代码来理解Java中的volatile关键字。
思路是使用两个线程来递增Runner类的count字段的值。Helper类实现了Runnable,在run方法中递增计数,其中count是静态和volatile的。
class Helper implements Runnable{ @Override public void run() { for(int i=0; i<100000;i++){ Runner.count+=1; } } } public class Runner { public static volatile long count=0; // to be incremented public static void main(String[] args){ Thread t1 = new Thread( new Helper()); Thread t2 = new Thread( new Helper()); t1.start(); t2.start(); try { t1.join(); t2.join(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Count= "+count); // output expected to be 200000 } }
预期的每次运行输出都是Count = 200000,但有时我会得到不同的数字。
请帮助我了解这是如何可能的。
admin 更改状态以发布 2023年5月24日