我正在尝试创建一个演示信号量使用的小程序。我创建了 2 个线程,它们运行两个 Farmer 实例:一个使用字符串“north”作为参数,一个使用“south”。它们似乎同时完成,而不是先完成 1 个线程,然后再完成第 2 个线程(如输出所示:
农夫过桥,往北
农夫过桥,往南
农夫过桥,现在往北
农夫过桥,现在往南
谁能告诉我我在这里做错了什么?
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();
}
}
}
}