信号量不起作用

Anu*_*bis 0 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();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*ven 5

每个 Farmer 都在创建自己的信号量,这意味着它可以独立于任何其他人获取和释放信号量。

改变这个:

private final Semaphore bridge = new Semaphore(1);
Run Code Online (Sandbox Code Playgroud)

对此:

private final static Semaphore bridge = new Semaphore(1);
Run Code Online (Sandbox Code Playgroud)

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