Multithreading of volatile

 

//volatile ensures the transparency of thread variables
public class Volatil {
 volatile int x =0; // threads share memory variables and can get the last written value
 private int y = 0;
 
  private void write() {
   x = 5;
   y = 1;
  }
   
  private void read() {
   int dummy = y;
   while (x != 5) {
    System.out.println("..." + y + " dummy=" + dummy); //dummy and y Values ​​are not equal
   }
  }

 public static void main(String[] args) throws Exception {
  final Volatil v = new Volatil();
  Thread t1 = new Thread(
   new Runnable() {
    public void run() {
     v.write();
    }
   }
  );
  Thread t2 = new Thread(
   new Runnable() {
    public void run() {
     v.read();
    }
   }
  );
  
  t2.start();
  t1.start();

  t1.join();
  t2.join();
  System.out.println("x="+v.x + "  y="+v.y);
  System.out.println("***** over ***");
  
 }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326032213&siteId=291194637