多线程之Single Threaded Execution design pattern(单线程执行设计模式)

一次只让一个线程进入

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();
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值