正确运用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. ...
随机推荐
- Quality Trimming Via Trimmomatic
已经去除接头(adapter) java -jar trimmomatic.jar PE -threads 20 -phred33 \ left.fastq.gz right.fastq.gz \ l ...
- C++之再续前缘(一)——C++基础(与C语言的差异)(下)
1.void型指针 void本身是一种数据类型,通常表示无值,不能声明void类型的变量,但是可以声明void类型的指针, void*类型的指针表示不确定的类型,是一种通用型的指针,也就是说任何类型的 ...
- Hive 中的分号问题
1. hive表中有一列值,是以 分号 ; 为分隔符连接存储的 1470047164;1470047628;1470049068;1470048978;1470048922;1470047658;1 ...
- 73.Android之SparseArray替代HashMap
转载:https://liuzhichao.com/p/832.html HashMap是java里比较常用的一个集合类,我比较习惯用来缓存一些处理后的结果.最近在做一个Android项目,在代码中定 ...
- bzoj3669[Noi2014]魔法森林
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #i ...
- cmd 利用IE打开网页
"C:\Program Files\Internet Explorer\iexplore.exe" "http://dmsite.chinacloudsites.cn/r ...
- Linux安装pdo_mysql模块
网站不能访问 查看apache日志 PHP Fatal error: Uncaught exception 'PDOException' with message 'could not find dr ...
- CF 444C DZY Loves Physics(图论结论题)
题目链接: 传送门 DZY Loves Chemistry time limit per test1 second memory limit per test256 megabytes Des ...
- HTML 速查列表
HTML 基本文档 <!DOCTYPE html> <html> <head> <title>文档标题</title> </head& ...
- Objective-C学习笔记之for( int )机制
NSArray *myArray = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4&q ...