直奔主题, Single Thread Execution也称作Critical Section(临界区),范例如下:

public class SingleThreadGate {
public static void main(String[] args) {
System.out.println("ctrl + c to exit."); Gate gate = new Gate();
new UserThread(gate, "Alice", "Alaska").start();
new UserThread(gate, "Bobby", "Brazil").start();
new UserThread(gate, "Chris", "Canada").start();
}
} class Gate{
private int count;
private String name;
private String address; public void pass(String name, String address){
this.count++;
this.name=name;
this.address=address; check();
} public void check() {
if (name.charAt(0) != address.charAt(0)) {
System.out.println("*******BROKEN *******" + toString());
}
} @Override
public String toString() {
return "No." + count + " " + name + ", " + address;
} } class UserThread extends Thread{
private Gate gate;
private String name;
private String address; public UserThread(Gate gate, String name, String address){
this.gate=gate;
this.name=name;
this.address=address;
} @Override
public void run() {
System.out.println(name+":begin->");
while(true){
gate.pass(name,address);
Thread.yield();
}
}
}

执行之后,会发现ou一很多broken,因为在执行pass的时候成员变量被其他线程改变了,所以判断name和address不一致,另外toString方法也存在同样的问题,执行过程中 name和address也随时被其他线程改变,所以会导致同一条记录的name和address也不一致,结果如下:

ctrl + c to exit.
Alice:begin->
Chris:begin->
Bobby:begin->
*******BROKEN *******No. Bobby, Brazil
*******BROKEN *******No. Chris, Canada
*******BROKEN *******No. Bobby, Brazil
*******BROKEN *******No. Bobby, Brazil
*******BROKEN *******No. Alice, Canada
*******BROKEN *******No. Chris, Alaska
*******BROKEN *******No. Alice, Canada
*******BROKEN *******No. Bobby, Brazil
*******BROKEN *******No. Chris, Alaska
*******BROKEN *******No. Bobby, Brazil
*******BROKEN *******No. Chris, Alaska
*******BROKEN *******No. Bobby, Brazil

那么如何改进呢?将pass方法加上synchronized关键字,这样就不会有任何错误了。不过这还不能保证整个gate类的所有方法都是安全的,当调用toString方法时还是会有同样的name与address不一致的问题,所以在toString方法上也要加上synchronized关键字,那么check方法还需要么?答案是不需要,因为check方法时私有的,外部无法访问,而且check方法是被pass方法调用的,而pass方法已经同步了,一个类中的synchronized关键之都是锁定的同一对象(this),所以不需要二次锁定,浪费性能。

synchnronized关键字也可以理解成把方法变成原子性操作,在java中,基本数据类型(primitive)如int, char, byte等都是原子性操作的,但是long和double则不一定,所以我们想把long和double这类非原子性类型按照原子性方式操作,需要加上关键字volatile,这样就可以了。

Single Thread Execution 能通过这座桥的只有一个人的更多相关文章

  1. 多线程系列之二:Single Thread Execution 模式

    一,什么是SingleThreadExecution模式?同一时间内只能让一个线程执行处理 二,例子 1.不安全的情况 用程序模拟 三个人频繁地通过一个只允许一个人经过的门.当人通过时,统计人数便会增 ...

  2. Single Thread Execution设计模式

    public class Test { public static void main(String[] args){ // FlightSercurityTest.test(); // EatNoo ...

  3. 多线程设计模式(一) Single Threaded Execution

    这里有一座独木桥.因为桥身非常的细,一次只能允许一个人通过.当这个人没有下桥,另一个人就不能过桥.如果桥上同时又两个人,桥就会因为无法承重而破碎而掉落河里. 这就是Single Threaded Ex ...

  4. 多线程程序设计学习(2)之single threaded execution pattern

    Single Threaded Execution Pattern[独木桥模式] 一:single threaded execution pattern的参与者--->SharedResourc ...

  5. JAVA并发设计模式学习笔记(二)—— Single Threaded Execution Pattern

    注:本文的主要参考资料为结城浩所著<JAVA多线程设计模式>. 单线程执行模式(Single Threaded Execution Pattern)是最简单的多线程设计模式,几乎所有其他的 ...

  6. 多线程学习之一独木桥模式Single Threaded Execution Pattern

    Single Threaded Execution Pattern[独木桥模式] 一:single threaded execution pattern的参与者--->SharedResourc ...

  7. How does a single thread handle asynchronous code in JavaScript?

    原文:https://www.quora.com/How-does-a-single-thread-handle-asynchronous-code-in-JavaScript ----------- ...

  8. Current thread must be set to single thread apartment (STA) mode before OLE,当前线程不在单线程单元中,因此无法实例化 ActiveX 控件“8856f961-340a-11d0-a96b-00c04fd705a2”。

    Add the STAThreadAttribute attribute on the Main method. This attribute is required if your program ...

  9. C# Current thread must be set to single thread apartment (STA) mode before OLE calls can be made

    将箭头指向部分替换为编译器报错的内容即可. 参考文章:https://www.experts-exchange.com/questions/28238490/C-help-needed-Current ...

随机推荐

  1. NX二次开发-UFUN输出UF函数使用错误UF_get_fail_message

    #include <uf.h> #include <uf_ui.h> #include <uf_modl.h> UF_initialize(); UF_FEATUR ...

  2. NX二次开发-UFUN获取图层类别的信息UF_LAYER_ask_category_info

    1 NX11+VS2013 2 3 #include <uf.h> 4 #include <uf_ui.h> 5 #include <uf_layer.h> 6 7 ...

  3. NX二次开发-C++的vector用法

    #include <algorithm> //vector排序去重 sort( BoxNum.begin(), BoxNum.end()); BoxNum.erase(unique(Box ...

  4. fabric.js 限制缩放的最大最小比例

    var rect = new fabrics.Rect({ v: true, top: 216, left: 384, width: 160, height: 90, fill: 'transpare ...

  5. 玩转gulp之watch监听文件自动编译

    博客移至 https://www.dodoblog.cn/blog?id=5befc928e0feb34495b57035 我们在写页面的时候,用到sass less等css预处理器的时候,虽然写的很 ...

  6. iOS7 AVAudioRecorder不能录音

    今天写录音代码的时候,在iOS7以下就可以录音,但是iOS7上不可以,后来才知道iOS7录音方式变了,加上下面的代码就可以了,bingo AVAudioSession *audioSession = ...

  7. CentOS7 相关配置

    nginx 1.在线安装nginx yum install nginx 2.启动nginx服务 systemctl start nginx 3.防火墙设置 打开http防火墙:firewall-cmd ...

  8. table 单列宽度设置

    参考:https://blog.csdn.net/lunhui1994_/article/details/81120579 效果: html: <!DOCTYPE html> <ht ...

  9. eclipse导出说明文档

    选中项目--右键--Export--Java--Javadoc—Finish 1.为程序添加文档注释 2.选中项目--右键Export--Java--Javadoc--next, 3.next--在V ...

  10. Android开发 SeekBar开发记录

    前言 开发记录博客不是讲解使用博客,更多的是各种功能与点子的记录 基本使用 <SeekBar android:layout_width="match_parent" andr ...