正确运用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和二次判断 实现多线程安全的更多相关文章

  1. python3.4学习笔记(二) 类型判断,异常处理,终止程序

    python3.4学习笔记(二) 类型判断,异常处理,终止程序,实例代码: #idle中按F5可以运行代码 #引入外部模块 import xxx #random模块,randint(开始数,结束数) ...

  2. Java问题记录——循环里的二次判断与状态更新

    Java问题记录——循环里的二次判断与状态更新 摘要:本文主要记录了在循环操作时可能出现的问题. 问题重现 在使用循环结构时,如果使用了定时任务,或者代码会多次调用循环结构,可能会导致有些对象会被循环 ...

  3. Synchronized之二:synchronized的实现原理

    Java提供了synchronized关键字来支持内在锁.Synchronized关键字可以放在方法的前面.对象的前面.类的前面. 当线程调用同步方法时,它自动获得这个方法所在对象的内在锁,并且方法返 ...

  4. python--基础学习(二)判断 、循环、定义函数、继承、调用

    1.判断 if.elif 代码示范 # coding=utf-8 score = 90 if (score>=90): print("完美") print("优秀& ...

  5. bash脚本编程之二 条件判断and 逻辑运算

    1.条件测试结构 1) if/then结构: 判断命令列表的退出码是否为0,0为成功. 如果if和then在条件判断的同一行上的话, 必须使用分号来结束if表达式: if和then都是关键字. 关键字 ...

  6. python语法(二)— 判断

    昨天简单的学习了一些python的一些简单的语句与python的数据类型,今天继续学习python的基础语句 if 语句. 一.if 语句 if 语句语法 if expression: ifSuite ...

  7. JAVA Synchronized (二)

    一,介绍 本文介绍JAVA多线程中的synchronized关键字作为对象锁的一些知识点. 所谓对象锁,就是就是synchronized 给某个对象 加锁.关于 对象锁 可参考:这篇文章 二,分析 s ...

  8. 并发编程之synchronized(二)------jvm对synchronized的优化

    一.锁的粗化 看如下代码 public class Test { StringBuffer stb = new StringBuffer(); public void test1(){ //jvm的优 ...

  9. 5-3 bash脚本编程之二 条件判断

    1. 条件测试的表达式 1. [ expression ]  :注意这个中括号的前后都有一个空格 2. [[ expression ]] 3. test expression 2.条件判断的类型 1. ...

随机推荐

  1. 【poj1386】 Play on Words

    http://poj.org/problem?id=1386 (题目链接) 题意 给出n个单词,判断它们能否首尾相接的排列在一起. Solution 将每一格单词的首字母向它的尾字母连一条有向边,那么 ...

  2. xcoj 1208 矩阵

    赛场上一开始以为是递推,交了一发希望以为能卡着线过(毕竟是O(5N)的),结果WA了. 又以为是dp,最后半小时尝试各种YY...各种WA 实际上取每次transfer中最大的概率然后递推是不对的.. ...

  3. glibc resolv/res_send.c getaddrinfo() buffer stack smash when dealing malformation big DNS Response Package

    catalogue . 漏洞简述 . 调试环境搭建 . 漏洞利用 . 漏洞分析 . 缓解修复方案 1. 漏洞简述 0x1: 函数调用顺序 getaddrinfo (getaddrinfo.c) -&g ...

  4. rsync服务器安装配置

    #rsync指定端口号(10002)1 rsync -e 'ssh -p 10002' rsync (server -- client) #2014-3-3 -----------server---- ...

  5. Swift 函数做参数和闭包做参数的一个细节差别

    函数作参数,示例为传入一个String和一个添加前缀的函数,返回一个添加完前缀的String: func demo(str:String,addPrefix:(String)->String)- ...

  6. Java Servlet完全教程

    Servlet 是一些遵从Java Servlet API的Java类,这些Java类可以响应请求.尽管Servlet可以响应任意类型的请求,但是它们使用最广泛的是响应web方面的请求. Servle ...

  7. Android配置文件,所有权限

    访问登记属性 android.permission.ACCESS_CHECKIN_PROPERTIES ,读取或写入登记check-in数据库属性表的权限 获取错略位置 android.permiss ...

  8. 整理CSS引发的相关理论的梳理

    写在前面 因为原先项目中的CSS样式乱得不行,所以领导决定要花大时间整理一下样式,也为了后续维护起来方便.其实也苦了自己,想想也是一件多烦的事情,烦的原因并非是说这件事情做起来没有意义,而是觉得这样的 ...

  9. python 培训之 装饰器

    1. 高阶函数 接收 函数作为参数,返回函数. 2. 函数闭包 3. 接收一个函数为参数,对其进行包装,然后返回一个包装函数(tip:包装函数中调用并返回参数函数. #! /usr/env/pytho ...

  10. css002 创建样式和样式表

    创建样式和样式表 一个样式表包含多个样式 样式表的种类 1.内部样式表,存放在<head></head>之间.如: <head> <style>   ( ...