我想創建一個小程序,演示使用信號量。我創建了2個線程,運行Farmer的兩個實例:一個以字符串「north」作爲參數,另一個以「south」作爲參數。相反,具有1周線程完成,隨後第二,他們似乎都在同一時間(如indictated由輸出完成:信號量不會工作
農民要過了橋,向北
農民要過了橋,向南
農民已經過了橋,現在向北
農民已經過了橋,現在向南
誰能告訴我什麼I'm做錯了什麼?
import java.util.concurrent.Semaphore;
public class Farmer implements Runnable
{
private String heading;
private final Semaphore bridge = new Semaphore(1);
public Farmer(String heading)
{
this.heading = heading;
}
public void run()
{
if (heading == "north")
{
try
{
//Check if the bridge is empty
bridge.acquire();
System.out.println("Farmer going over the bridge, heading north");
Thread.sleep(1000);
System.out.println("Farmer has crossed the bridge and is now heading north");
bridge.release();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
//Farmer crossed the bridge and "releases" it
}
else if (heading == "south")
{
try
{
//Check if the bridge is empty
bridge.acquire();
System.out.println("Farmer going over the bridge, heading south");
Thread.sleep(1000);
//Farmer crossed the bridge and "releases" it
System.out.println("Farmer has crossed the bridge and is now heading south");
bridge.release();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
此外,您正在使用==來進行字符串比較,這絕不是一個好主意。你應該使用'equals(...)'。我看到「北」和「北」 – Gray