信号量不起作用

时间:2012-09-30 15:28:48

标签: java multithreading semaphore

我正在尝试创建一个演示信号量使用的小程序。我创建了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();
            }
        }
    }
}

1 个答案:

答案 0 :(得分:4)

每个农民都在创建自己的信号量,这意味着它可以独立于任何其他信号获取和发布信号量。

改变这个:

private final Semaphore bridge = new Semaphore(1);

到此:

private final static Semaphore bridge = new Semaphore(1);

然后,所有Farmer实例之间将共享信号量。