new Semaphore(0)

来源:13-13 打怪升级之路总结

暮色朝晖

2020-04-06

class FooBar {
private int n;

public FooBar(int n) {
    this.n = n;
}

Semaphore foo = new Semaphore(1);
Semaphore bar = new Semaphore(0);

public void foo(Runnable printFoo) throws InterruptedException {
    for (int i = 0; i < n; i++) {
        foo.acquire();
        printFoo.run();
        bar.release();
    }
}

public void bar(Runnable printBar) throws InterruptedException {
    for (int i = 0; i < n; i++) {
        bar.acquire();
        printBar.run();
        foo.release();
    }
}

}
老师,这是我在leetcode上面看到的一道题,这个Semaphore bar = new Semaphore(0)是什么用法,0个信号量?起什么特殊作用?

写回答

1回答

悟空

2020-04-06

0是可以的  保证先运行foo的for循环的第一次  然后会释放一个许可证,就变成1了
1
0

深度解密Java并发工具,精通JUC,成为并发多面手

JUC全方位讲解,构建并发工具类知识体系

1599 学习 · 573 问题

查看课程