Single Threaded Execution----能通过这座桥的,只有一个人
当有一座小桥,每次只能通过一个人,如果同时有两个人在桥上,桥会断开如今有三个姓和名的首字母相同的人多次通过此桥
package com.quest.mchen2.thread.single_thread_execution;public class Gate { private int counter=0; private String name= "Nobody"; private String address= "Nowhere"; //为了防止多线程情况下对象先后交叉执行,从而导致将共享实例的字段改写了 public synchronized void pass(String name, String address){ this. counter++; this. name=name; this. address=address; check(); } @Override public synchronized String toString() { // TODO Auto-generated method stub return "No."+ counter+ ":"+ name+ ", "+ address; } private void check(){ if( name.charAt(0)!= address.charAt(0)){ System. out.println( "*****BROKEN*****" +toString()); } }}package com.quest.mchen2.thread.single_thread_execution;public class UserThread extends Thread{ private final Gate gate; private final String myname; private final String myaddress; public UserThread(Gate gate, String myname, String myaddress){ this. gate=gate; this. myname=myname; this. myaddress=myaddress; } @Override public void run() { // TODO Auto-generated method stub System. out.println( myname+ " BEGIN"); while( true){ gate. pass( myname, myaddress); } } }package com.quest.mchen2.thread.single_thread_execution;public class Main { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System. out.println( "Testing Gate, hit 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(); }}
由于在Gate类的pass方法加上了synchronized 所以可以阻止name与address的首字母出现的情况
toString()加上synchronized是因为当别的线程X调用toString。线程X在引用name字段的值之后到引用addresszi字段之间,UserThread的线程
可能会改掉address的值,这样一来,toString方法可能对线程使用name与address第一个字母不一致的值来构成字符串