volatile does not guarantee thread safety in java

  • 2020-10-07 18:42:43
  • OfStack

Today a dozen code studied under 1 java volatile keyword can not guarantee thread safety, through practice, volatile is cannot ensure thread safety, it is just to ensure the data visibility, won't cache, each thread read data from main memory, rather than the data read from the cache, attach the HTML code is as follows, when synchronized removed, the results of each thread is disorderly, and the result is right.


/**
 * 
 *  Brief description of class 
 * 
 * <p>
 *  Class description 
 * </p>
 * 
 * @author think
 * 
 */

public class VolatileThread implements Runnable {

 private volatile int a = 0;

 @Override
 public void run() {
  // TODO Auto-generated method stub
//  synchronized (this) {
   a = a + 1;
   System.out.println(Thread.currentThread().getName() + ":----" + a);
   try {
    Thread.sleep(100);
    a = a + 2;
   } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

   System.out.println(Thread.currentThread().getName() + ":----" + a);
//  }
 }

}

/**
 * 
 *  Brief description of class 
 * 
 * <p>
 *  Class description 
 * </p>
 * 
 * @author think
 * 
 */

public class VolatileMain {

 public static void main(String[] args) {

  VolatileThread s = new VolatileThread();

  Thread t1 = new Thread(s);
  Thread t2 = new Thread(s);
  Thread t3 = new Thread(s);
  Thread t4 = new Thread(s);
  t1.start();
  t2.start();
  t3.start();
  t4.start();
  
  
/*   Synchronous result 
  Thread-2:----1
  Thread-2:----3
  Thread-0:----4
  Thread-0:----6
  Thread-3:----7
  Thread-3:----9
  Thread-1:----10
  Thread-1:----12*/
  
/*  
   Remove the result of synchronization 
  Thread-0:----1
  Thread-1:----2
  Thread-2:----3
  Thread-3:----4
  Thread-0:----8
  Thread-3:----10
  Thread-1:----10
  Thread-2:----12*/
  


 }

}

Related articles: