Home > Java > javaTutorial > An example explanation of the problem that volatile cannot guarantee thread safety in Java

An example explanation of the problem that volatile cannot guarantee thread safety in Java

巴扎黑
Release: 2017-09-05 14:21:26
Original
2141 people have browsed it

The following editor will bring you an article that volatile cannot guarantee thread safety in Java (explanation with examples). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

Today I coded and studied whether Java’s volatile keyword can guarantee thread safety. After practice, volatile cannot guarantee thread safety, it only guarantees data. The visibility will not be cached again. Each thread reads data from the main memory, not from the cache. The code is attached as follows. When synchronized is removed, the result of each thread is It's messy, but the result is correct when you add it.


/**
 * 
 * 类简要描述
 * 
 * <p>
 * 类详细描述
 * </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);
//  }
 }

}
Copy after login


/**
 * 
 * 类简要描述
 * 
 * <p>
 * 类详细描述
 * </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();
  
  
/*  同步的结果
  Thread-2:----1
  Thread-2:----3
  Thread-0:----4
  Thread-0:----6
  Thread-3:----7
  Thread-3:----9
  Thread-1:----10
  Thread-1:----12*/
  
/*  
  去掉同步的结果
  Thread-0:----1
  Thread-1:----2
  Thread-2:----3
  Thread-3:----4
  Thread-0:----8
  Thread-3:----10
  Thread-1:----10
  Thread-2:----12*/
  


 }

}
Copy after login

The above is the detailed content of An example explanation of the problem that volatile cannot guarantee thread safety in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template