Single Threaded Execution
2016-04-19 00:00
435 查看
摘要: 对临界区的修改只允许一个线程操作
Single Threaded Execution
这个设计模式是多线程设计时候最基础的一个准则,对于临界区的值只允许一个线程进行修改。定义临界区还是使用synchronized来定义。(虽然jdk 7出了很多并发包api,但还是先只关注最基础的api 关键字)
因为定义了临界区,所以不会输出check里面的值。去掉关键字就会出错。
但是定义临界区,就会使多线程的性能降低。如何减小临界区的范围是一个比较关键的地方。像多个值需要赋值的时候,volatile 关键字是并没有任何作用的。
Single Threaded Execution
这个设计模式是多线程设计时候最基础的一个准则,对于临界区的值只允许一个线程进行修改。定义临界区还是使用synchronized来定义。(虽然jdk 7出了很多并发包api,但还是先只关注最基础的api 关键字)
//演示 public class Main { public static void main(String args[]){ Gate gate=new Gate(); new UserThread(gate,"chen ","china").start(); new UserThread(gate,"bob","brazil").start();; } } public class Gate { private int counter=0; private String name="nobady"; private String address="nowhere"; public synchronized void pass(String name,String address){ this.counter++; this.name=name; this.address=address; check(); } public String toString(){ return "no."+counter+": "+name+","+address; } public void check(){ if(name.charAt(0)!=address.charAt(0)){ System.out.println("******broken******"+toString()); } } } public class UserThread extends Thread { private final Gate gate; private final String myname; private final String myaddress; public UserThread(Gate gate,String name,String address) { this.gate=gate; this.myname=name; this.myaddress=address; } public void run(){ System.out.println(myname+" begin"); while(true){ gate.pass(myname, myaddress); } } }
因为定义了临界区,所以不会输出check里面的值。去掉关键字就会出错。
但是定义临界区,就会使多线程的性能降低。如何减小临界区的范围是一个比较关键的地方。像多个值需要赋值的时候,volatile 关键字是并没有任何作用的。
相关文章推荐
- Immutable
- Guarded Suspension
- balking
- PHP的微博微信QQ空间人人网分享的接口
- oracle使用过程遇到的小问题及解决方法
- reactiveCocoa
- swift和oc混编
- JS对cookie的操作方式
- httpSession 和 hibernate Session的区别
- nginx reload 命令报:nginx: [error] invalid PID number
- jQuery 追加元素方法
- junit4 单元测试
- uikeyboard所在uiwindow
- 怎么通过iMindMap的使用成为优秀的内容作家
- Effective C++: std::weak_ptr
- “师兄帮帮堂”正式成立
- 外循环与内循环的分析演示
- 堡垒机集中管控平台-麒麟开源堡垒机简介
- tar命令
- DIGITS的安装与使用记录