我想创建一个小程序,演示使用信号量。我创建了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