博客
关于我
java中volatile不能保证线程安全
阅读量:371 次
发布时间:2019-03-04

本文共 1657 字,大约阅读时间需要 5 分钟。

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

 

/** *  * 类简要描述 *  * 

* 类详细描述 *

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

* 类详细描述 *

* * @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*/ }}

 

转载地址:http://pnvr.baihongyu.com/

你可能感兴趣的文章
nestJS学习
查看>>
net core 环境部署的坑
查看>>
NET Framework安装失败的麻烦
查看>>
Net 应用程序如何在32位操作系统下申请超过2G的内存
查看>>
Net.Framework概述
查看>>
NET3.0+中使软件发出声音[整理篇]<转>
查看>>
net::err_aborted 错误码 404
查看>>
NetApp凭借领先的混合云数据与服务把握数字化转型机遇
查看>>
NetAssist网络调试工具使用指南 (附NetAssist工具包)
查看>>
Netbeans 8.1启动参数配置
查看>>
NetBeans IDE8.0需要JDK1.7及以上版本
查看>>
NetBeans之JSP开发环境的搭建...
查看>>
NetBeans之改变难看的JSP脚本标签的背景色...
查看>>
netbeans生成的maven工程没有web.xml文件 如何新建
查看>>
netcat的端口转发功能的实现
查看>>
NetCore 上传,断点续传,可支持流上传
查看>>
Netcraft报告: let's encrypt和Comodo发布成千上万的网络钓鱼证书
查看>>
Netem功能
查看>>
netfilter应用场景
查看>>
Netflix:当你按下“播放”的时候发生了什么?
查看>>