package org.example.mianshi.concurrent; /** * 线程不安全例子,共享数据sharedstate * @author lifuchun */ public class threadsafesample { public int sharedstate; public void nonsafeaction() { while (sharedstate < 100000) { int former = sharedstate++; int latter = sharedstate; if (former != latter - 1) { system.out.printf("observed data race, former is " + former + ", " + "latter is " + latter); } } } public static void main(string[] args) throws interruptedexception { final threadsafesample sample = new threadsafesample(); thread threada = new thread() { @override public void run() { sample.nonsafeaction(); } }; thread threadb = new thread() { @override public void run() { sample.nonsafeaction(); } }; threada.start(); threadb.start(); threada.join(); threadb.join(); } }
本篇对比了sychronized和reetrantlock的区别;
然后说了线程安全的概念和保证线程手段。
原创不易,转载请注明出处。
如对本文有疑问, 点击进行留言回复!!
unity的错误解决办法:NullReferenceException: Object reference not set to an instance of an object;tiny proje
Hadoop 之 HDFS (HDFS 数据流的 读写 流程)
听说你一读Spring源码就懵逼?我帮你把架子搭好了,你填就行!
首席架构师推荐:金融保险领域数字化转型实践--如何优雅地修改业务中台中分层应用Maven多模块的版本号?(命令导入式)
[JVM学习之路]一、初识JVM,了解其结构、模型及生命周期
网友评论