首页 > 编程 > Java > 正文

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

2019-11-26 11:30:15
字体:
来源:转载
供稿:网友

今天打了打代码研究了一下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不能保证线程安全(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表