一次只让一个线程进入
public class Userr extends Thread {
private final String myname;
private final String myaddress;
private final Gate gate;
public Userr(String myname,String myaddress,Gate gate){
this.myname=myname;
this.myaddress=myaddress;
this.gate=gate;
}
@Override
public void run(){
System.out.println("我的名字:"+myname);
//方便看到效果
while (true){
this.gate.pass(myname,myaddress);
}
}
}
public class Gate {
private static 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;
verify();
}
//当条件不满足时,进行toString打印。
private void verify(){
if (this.name.charAt(0) != this.address.charAt(0)) {
try {
Thread.sleep(500);
System.out.println("*******BROKEN********" + toString());
}catch (Exception e){
}
}
}
@Override
public String toString() {
return "第"+counter + "个,名字:" + name + "地址:" + address ;
}
}
public static void main(String [] args){
Gate gate = new Gate();
Userr sh = new Userr("ShangHai","Shang上海",gate);
Userr bj = new Userr("eiJing","Bei北京",gate);
Userr hf = new Userr("HeFei","e合肥",gate);
hf.start();
sh.start();
bj.start();
}