当前位置: 移动技术网 > IT编程>开发语言>Java > java中volatile不能保证线程安全(实例讲解)

java中volatile不能保证线程安全(实例讲解)

2019年07月19日  | 移动技术网IT编程  | 我要评论

今天打了打代码研究了一下java的volatile关键字到底能不能保证线程安全,经过实践,volatile是不能保证线程安全的,它只是保证了数据的可见性,不会再缓存,每个线程都是从主存中读到的数据,而不是从缓存中读取的数据,附上代码如下,当synchronized去掉的时候,每个线程的结果是乱的,加上的时候结果才是正确的。

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

}
/**
 * 
 * 类简要描述
 * 
 * <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*/
  


 }

}

以上这篇java中volatile不能保证线程安全(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网