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 关键字是并没有任何作用的。