正确运用synchronized和二次判断 实现多线程安全
正确运用synchronized和二次判断 实现多线程安全,做出高效二符合预期的程序,特别是多个线程跑一个对象的时候,如下图所示:
测试代码如下:
特别注意if(shutdownRequested){ *部分不同的写法。
不然就会输出与逻辑不符的现象:
如:
runner—-false—-我没有关闭。。。
runner—-true—-我没有关闭。。。
runner—-true—-我关闭了=====»>
package com.xue.gang.volatiler;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class VolatileRunner{
public static void main(String args[]) throws InterruptedException {
int size=1000;
CountDownLatch countDownLatch = new CountDownLatch(size);
TomRunner tomRunner = new TomRunner(false,countDownLatch,"runner");
ExecutorService executorService = Executors.newCachedThreadPool();
for(int i=1;i<=size;i++){
executorService.execute(new Thread2RunTomRunner(countDownLatch,tomRunner,i+"_号"));
}
countDownLatch.await();
executorService.shutdown();
//new Thread(volatileRunner).start();
}
static class Thread2RunTomRunner implements Runnable{
private CountDownLatch countDownLatch;
private TomRunner tomRunner;
private String name;
public Thread2RunTomRunner(CountDownLatch countDownLatch,
TomRunner tomRunner, String name) {
super();
this.countDownLatch = countDownLatch;
this.tomRunner = tomRunner;
this.name = name;
}
public void run() {
System.out.println(this.name+":running...");
this.tomRunner.doWork();
System.out.println(this.name+":结束...");
this.countDownLatch.countDown();
}
}
static class TomRunner{
volatile boolean shutdownRequested = false;
//boolean shutdownRequested = false;
String name;
public TomRunner(boolean shutdownRequested,
CountDownLatch countDownLatch, String name) {
super();
this.shutdownRequested = shutdownRequested;
this.name = name;
}
public void shutdown() {
this.shutdownRequested = true;
}
public void doWork() {
while (true) {
/**
*多个线程的代码去执行: System.out.println(this.name + "----" + this.shutdownRequested +"----" +"我没有关闭。。。");
* */
/*if(shutdownRequested){
System.out.println(this.name + "----" + this.shutdownRequested +"----" +"我关闭了=====>>>");
break;
}else{
System.out.println(this.name + "----" + this.shutdownRequested +"----" +"我没有关闭。。。");
shutdown();
}*/
/**
* 如果没有二次判断,也会出现比较脏数据.
* */
/*
if(shutdownRequested){
System.out.println(this.name + "----" + this.shutdownRequested +"----" +"我关闭了=====>>>");
break;
}
synchronized (this) {
System.out.println(this.name + "----" + this.shutdownRequested +"----" +"我没有关闭。。。");
shutdown();
}*/
/**
* 加上二次判断,能够正确
* */
if(shutdownRequested){
System.out.println(this.name + "----" + this.shutdownRequested +"----" +"我关闭了=====>>>");
break;
}
synchronized (this) {
if(!shutdownRequested){
System.out.println(this.name + "----" + this.shutdownRequested +"----" +"我没有关闭。。。");
shutdown();
}
}
}
}
}
}
原:http://my.oschina.net/u/177808/blog/165442
正确运用synchronized和二次判断 实现多线程安全的更多相关文章
- python3.4学习笔记(二) 类型判断,异常处理,终止程序
python3.4学习笔记(二) 类型判断,异常处理,终止程序,实例代码: #idle中按F5可以运行代码 #引入外部模块 import xxx #random模块,randint(开始数,结束数) ...
- Java问题记录——循环里的二次判断与状态更新
Java问题记录——循环里的二次判断与状态更新 摘要:本文主要记录了在循环操作时可能出现的问题. 问题重现 在使用循环结构时,如果使用了定时任务,或者代码会多次调用循环结构,可能会导致有些对象会被循环 ...
- Synchronized之二:synchronized的实现原理
Java提供了synchronized关键字来支持内在锁.Synchronized关键字可以放在方法的前面.对象的前面.类的前面. 当线程调用同步方法时,它自动获得这个方法所在对象的内在锁,并且方法返 ...
- python--基础学习(二)判断 、循环、定义函数、继承、调用
1.判断 if.elif 代码示范 # coding=utf-8 score = 90 if (score>=90): print("完美") print("优秀& ...
- bash脚本编程之二 条件判断and 逻辑运算
1.条件测试结构 1) if/then结构: 判断命令列表的退出码是否为0,0为成功. 如果if和then在条件判断的同一行上的话, 必须使用分号来结束if表达式: if和then都是关键字. 关键字 ...
- python语法(二)— 判断
昨天简单的学习了一些python的一些简单的语句与python的数据类型,今天继续学习python的基础语句 if 语句. 一.if 语句 if 语句语法 if expression: ifSuite ...
- JAVA Synchronized (二)
一,介绍 本文介绍JAVA多线程中的synchronized关键字作为对象锁的一些知识点. 所谓对象锁,就是就是synchronized 给某个对象 加锁.关于 对象锁 可参考:这篇文章 二,分析 s ...
- 并发编程之synchronized(二)------jvm对synchronized的优化
一.锁的粗化 看如下代码 public class Test { StringBuffer stb = new StringBuffer(); public void test1(){ //jvm的优 ...
- 5-3 bash脚本编程之二 条件判断
1. 条件测试的表达式 1. [ expression ] :注意这个中括号的前后都有一个空格 2. [[ expression ]] 3. test expression 2.条件判断的类型 1. ...
随机推荐
- python模块介绍二。
全局变量 全局变量 python在一个.py文件内部自动添加了一些全局变量 print(vars()) #查看当前的全局变量 执行结果: {'__package__': None, '__loader ...
- js-FCC算法-No repeats please字符串的全排列
把一个字符串中的字符重新排列生成新的字符串,返回新生成的字符串里没有连续重复字符的字符串个数.连续重复只以单个字符为准 例如, aab 应该返回 2 因为它总共有6中排列 (aab, aab, aba ...
- 【BZOJ-1597】土地购买 DP + 斜率优化
1597: [Usaco2008 Mar]土地购买 Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 2931 Solved: 1091[Submit] ...
- 【codevs1034】 家园
http://codevs.cn/problem/1034/ (题目链接) 题意 给出一张n个点的图,有m架飞船按照固定的航班运行,没单位时间移动一次,并且没收航班都有自己的容纳量.问从0号点将K个人 ...
- 【poj1014】 Dividing
http://poj.org/problem?id=1014 (题目链接) 题意 给出有分别价值为1,2,3,4,5,6的6种物品,输入6个数字,表示相应价值的物品的数量,问一下能不能将物品分成两份, ...
- Diccuz!NT的dll版本号控制技巧
dnt每次发布新版本时,公布出来的版本号都是3位数以上,拿3.6.711这个版本号的代码来说,几乎每一个dll上都是统一的版本号命名: 对于一个成熟的产品来说,统一一致的版本号命名有以下的好处: 1. ...
- Java 中常用缓存Cache机制的实现
所谓缓存,就是将程序或系统经常要调用的对象存在内存中,一遍其使用时可以快速调用,不必再去创建新的重复的实例.这样做可以减少系统开销,提高系统效率. 所谓缓存,就是将程序或系统经常要调用的对象存在内存中 ...
- BeautifulSoup高级应用 之 CSS selectors /CSS 选择器
BeautifulSoup支持最常用的CSS selectors,这是将字符串转化为Tag对象或者BeautifulSoup自身的.select()方法. 本篇所使用的html为: html_doc ...
- AngularJs angular.bind、angular.bootstrap、angular.copy
angular.bind 返回一个调用self的函数fn(self代表fn里的this).可以给fn提供参数args(*).这个功能也被称为局部操作,以区别功能. 格式:angular.bind(se ...
- python模块xlrd安装-处理excel文件必须
我安装了很久,网上查了很多资料,但都不太适合,综合 了一下,再写一写,希望有用... 官网下载xlrd:官网xlrd下载地址, 真的很难下,我用讯雷,有时候断断续续 下面是我的百度网盘地址,分享出来, ...