1
我想使用java库提供的信号量来实现这个经典的厕所入口问题。如何使用java信号量来实现这种并发情况?
情景是:有一个公共浴室,最多可以使用4名女性和5名男性,但从不同时使用。而且,至少有一名女性在等待,而男性则应该等待,这样女性才能入门。
到目前为止,我仿照这个并发类...
public class Concurrencia {
Semaphore mujeres; // Semaphore for women, initialized in 4
Semaphore hombres; // Semaphore for men, initialized in 5
public Concurrencia (Semaphore mujeres, Semaphore hombres) {
this.mujeres = mujeres;
this.hombres = hombres;
}
public synchronized void EntradaHombres() { // Method for men's entrance
if (mujeres.availablePermits() == 4 && !mujeres.hasQueuedThreads()) {
System.out.println("Entró un hombre al baño"); // Man gets in
try { hombres.acquire(); } catch (InterruptedException ex) { }
}
else {
System.out.println("Hombre en espera"); // Man should wait
}
}
public synchronized void EntradaMujeres() { // Method for women's entrance
if (hombres.availablePermits() == 5) {
System.out.println("Entró una mujer al baño"); // Woman gets in
try { hombres.acquire(); } catch (InterruptedException ex) { }
}
else {
System.out.println("Mujer en espera"); // Woman should wait
}
}
public synchronized void SalidaMujeres() {
System.out.println("Salió una mujer del baño");
mujeres.release(); // Woman gets out
}
public synchronized void SalidaHombres() {
System.out.println("Salió un hombre del baño");
hombres.release(); // Man gets out
}
这是一个奇怪的洗手间:-p – 2013-02-21 02:51:48
为什么你在'EntradaMujeres'的'hombre'信号灯上获取? – Perception 2013-02-21 03:02:11
我想象一下,使用信号量的关键是你不需要'synchronized'方法。如果一切都是同步的,那么你可以假装所有事情都发生在一个线程中。 – 2013-02-21 03:06:28