对于 Java,有一个非常好的标准库具有此功能:
http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/package-summary.html
只需使用 Semaphore 字段创建一个类:
class Server {
private static final MAX_AVAILABLE = 100;
private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
// ... put all other fields (OS, version) here...
private Server () {}
// add a factory method
public static Server getServer() throws InterruptedException {
available.acquire();
//... do the rest here
}
}
编辑:
如果您希望事情更“可配置”,请考虑使用 AOP 技术,即创建基于信号量的同步方面。
编辑:
如果您想要完全独立的系统,我想您可以尝试使用任何支持行级锁定作为信号量的现代数据库(例如 PostgreSQL)系统。例如,为每个代表一个服务器创建 3 行,如果它们是空闲的(例如“ select * from server where is_used = 'N' for update
”),则使用锁定选择它们,将所选服务器标记为已使用,最后取消标记,提交事务。