在多线程环境中,如何保证共享资源的合理使用。就可以引出这个设计模式。
场景:多个游客要验证身份后才能通过检票口
角色 | 作用 |
---|---|
Gate | 资源、 并提供方法使用资源 |
User | 使用资源的地方 |
Client | 模拟多个线程使用资源 |
代码演示:
public class Gate {
private String name;
private String address;
private int counter;
// synchronized 保证线程的安全性
public synchronized void pass(String name ,String address){
this.name = name;
this.address = address;
counter ++;
check();
}
private void check() {
//名称首字母一致放行、否则阻塞--
if(name.charAt(0)!= address.charAt(0)){
System.out.println("BROKEN * NO." + counter + toString());
}
}
@Override
public String toString() {
return " name =" + name + " address = " +address;
}
}
public class User extends Thread {
private String name,address;
private Gate gate;
public User(String name, String address, Gate gate) {
this.name = name;
this.address = address;
this.gate = gate;
}
@Override
public void run() {
System.out.println("user = [name : " + name + " address = " + address + " ]");
while (true){
gate.pass(name,address);
}
}
}
public class Client
{
public static void main(String[] args){
Gate gate = new Gate();
User bj = new User("BaoBao","Beijing",gate);
User sh = new User("ShangLao","Shanghai",gate);
User gz = new User("GuangLao","Guangzhou",gate);
bj.start();
sh.start();
gz.start();
}
}