[英]Semaphore won't work
我试图创建一个演示信号量用法的小程序。 我创建了2个线程,它们运行Farmer的两个实例:一个以字符串“ north”作为参数,另一个以“ south”。 他们似乎没有同时完成第一个线程和第二个线程,而是看起来都同时完成了(如输出所示:
农夫越过桥,往北走
农夫穿过桥,往南走
农夫已经过桥,现在正向北
农夫已经过桥,现在正向南
谁能告诉我我在做什么错?
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();
}
}
}
}
每个农民都在创建自己的信号量,这意味着它可以独立于任何其他人获取和释放它。
更改此:
private final Semaphore bridge = new Semaphore(1);
对此:
private final static Semaphore bridge = new Semaphore(1);
然后,该信号灯将在所有Farmer实例之间共享。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.