java - 信号量不起作用

标签 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();
            }
        }
    }
}

最佳答案

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

更改此:

private final Semaphore bridge = new Semaphore(1);

对此:

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

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

关于java - 信号量不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12662428/

相关文章:

java - 如何从 Firebase 获取特定键的特定子值

java - 将波形( float 组)作为声音播放

java - 是否有任何自动化工具可以对 java 批处理应用程序执行功能测试?

c# - Task.WaitAll 方法 (Task[], Int32) 过期时不释放线程

c++ - 多线程建议

c - 使用 POSIX 计数信号量作为二进制信号量

algorithm - 有人可以用 P V 形式解释生产者和消费者吗?

multithreading - 信号量值

java - 算法:从多个有序列表中搜索递增的整数序列

multithreading - 关于单元线程模型