以参加展会为例,大厅保安负责人数控制,进入的成员发放准入证,出来的成员收回准入证。

大厅保安:

import java.util.concurrent.Semaphore;
public class GuardLicense {
    private Semaphore licenses;
    public GuardLicense(int count) {
        licenses = new Semaphore(count);
    }
    
    public void join() {
        if (!licenses.tryAcquire()) {
            throw new UsersExceededException("All licenses are in use");
        }       
        System.out.println("Licenses left " + getAvailableLicenses());
    }
    
    public void exit() {
        licenses.release();
        System.out.println("Licenses left " + licenses.availablePermits());
    }
    
    public int getAvailableLicenses() {
        return licenses.availablePermits();
    }
}

访问者,访问者不仅有名字,还得跟保安接触,然后自己进去参加展会。

public class Visitor {
    private GuardLicense guardLicense;
    private String name;

    public Visitor(String name, GuardLicense guardLicense) {
        this.name = name;
        this.guardLicense = guardLicense;
    }

    public void join() {
        System.out.println(name + " joins");
        guardLicense.join();
    }

    public void exit() {
        System.out.println(name + " exists");
        guardLicense.exit();
    }
}

人员满额则会报警提示

public class UsersExceededException extends RuntimeException {

    public UsersExceededException(String msg) {
        super(msg);
    }
}

开始展览了:

public class SemaphoreExample {   
    public static void main(String[] args) {
        GuardLicense guardLicense = new GuardLicense(5);
        System.out.println("No. of licenses available: " + guardLicense.getAvailableLicenses());
        Visitor user1 = new Visitor("User1" , guardLicense);
        user1.join();
        Visitor user2 = new Visitor("User2" , guardLicense);
        user2.join();
        Visitor user3 = new Visitor("User3" , guardLicense);
        user3.join();
        Visitor user4 = new Visitor("User4" , guardLicense);
        user4.join();
        Visitor user5 = new Visitor("User5" , guardLicense);
        user5.join();
        Visitor user6 = new Visitor("User6" , guardLicense);
        try {
            user6.join();
        } catch (UsersExceededException e) {
            System.out.println(e.getMessage());
            user1.exit();           
        }
        
    }
}

运行结果如下:

No. of licenses available: 5
User1 joins
Licenses left 4
User2 joins
Licenses left 3
User3 joins
Licenses left 2
User4 joins
Licenses left 1
User5 joins
Licenses left 0
User6 joins
All licenses are in use
User1 exists
Licenses left 1

注意:用户和保安接触,这个里有点问题,得把保安塞入用户里面:

public Visitor(String name, GuardLicense guardLicense) {
        this.name = name;
        this.guardLicense = guardLicense;
    }

最初的面向对象思想,就是对象与对象之间传递消息。后来变成了这样,感觉这就是现在面向对象不好的地方吧。