博客
关于我
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/

你可能感兴趣的文章
mysql 5.6 修改端口_mysql5.6.24怎么修改端口号
查看>>
MySQL 8.0 恢复孤立文件每表ibd文件
查看>>
MySQL 8.0开始Group by不再排序
查看>>
mysql ansi nulls_SET ANSI_NULLS ON SET QUOTED_IDENTIFIER ON 什么意思
查看>>
multi swiper bug solution
查看>>
MySQL Binlog 日志监听与 Spring 集成实战
查看>>
MySQL binlog三种模式
查看>>
multi-angle cosine and sines
查看>>
Mysql Can't connect to MySQL server
查看>>
mysql case when 乱码_Mysql CASE WHEN 用法
查看>>
Multicast1
查看>>
mysql client library_MySQL数据库之zabbix3.x安装出现“configure: error: Not found mysqlclient library”的解决办法...
查看>>
MySQL Cluster 7.0.36 发布
查看>>
Multimodal Unsupervised Image-to-Image Translation多通道无监督图像翻译
查看>>
MySQL Cluster与MGR集群实战
查看>>
multipart/form-data与application/octet-stream的区别、application/x-www-form-urlencoded
查看>>
mysql cmake 报错,MySQL云服务器应用及cmake报错解决办法
查看>>
Multiple websites on single instance of IIS
查看>>
mysql CONCAT()函数拼接有NULL
查看>>
multiprocessing.Manager 嵌套共享对象不适用于队列
查看>>