线程在没有 volatile 的情况下无法工作,并从 RAM 读取值而不是缓存

问题描述

Volatile 应该让线程从 RAM 中读取值,禁用线程缓存,如果没有 volatile 缓存将被启用,使线程不知道由另一个线程,但这不适用于以下代码。

为什么会发生这种情况,并且代码在使用和不使用 volatile 关键字时都一样?

public  class Racing{
    
     private  boolean won = false;  //without volatile keyword
      
     public void race() throws InterruptedException{
        Thread one = new Thread(()->{
            System.out.println("Player-1 is racing...");
            while(!won){
              won=true;
            }
            System.out.println("Player-1 has won...");
        });
        
        Thread two=new Thread(()->{
           System.out.println("Player-2 is racing...");
            while(!won){
               System.out.println("Player-2 Still Racing...");
           } 
        });
        
        one.start();
        //Thread.sleep(2000);
        two.start();
      }
      
      public static void main(String k[]) {
        Racing racing=new Racing();
        try{
             racing.race();
        }
        catch(InterruptedException ie){}
      }
  

为什么这在有和没有 volatile 的情况下表现相同?

解决方法

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

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

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