为什么 Volatile Count 字段给出的结果少于 Java 中的循环次数?

问题描述

我试图理解 volatile 关键字并编写了一个虚拟程序来测试它。

public class SharedObjects {

    public static void main(String[] args) {
        MyRunnable runnable = new MyRunnable();

        Thread thread1 = new Thread(runnable,"Thread 1");
        Thread thread2 = new Thread(runnable,"Thread 2");

        thread1.start();
        thread2.start();

        System.out.printf("%s: %d\n",Thread.currentThread().getName(),runnable.count);
    }
}
public class MyRunnable implements Runnable {
    public volatile int count = 0;

    @Override
    public void run() {
        for (int i = 0; i < 1000000; i++) {
            count++;
        }

        System.out.printf("%s: %d\n",count);
    }
}

输出:

main: 1024
Thread 2: 831910
Thread 1: 902879

我觉得不管有没有volatile关键字,最后一个线程的结果至少应该是1000000(循环的次数),但是没有volatile关键字。

如果我删除 volatile 关键字,它总是给出一个至少为 1000000 的数字,例如

main: 1063
Thread 2: 1086742
Thread 1: 1086742

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)