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