0

我已经阅读了有关信号量的各种 帖子以及它们与互斥体的不同之处。在选择二进制信号量和同步块之间,我应该考虑哪些因素来做出决定?

问题陈述:https ://leetcode.com/problems/print-foobar-alternately/

Say there are two methods to print "Foo" and "Bar" and you want to print "Foo" and "Bar" alternatively for a given 'n'.

方法一:

使用同步块的解决方案

class FooBar {
    private int n;
    boolean shouldPrintFoo = true;

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

    public synchronized void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            while (!shouldPrintFoo) {
                wait();    
            }
            
            // printFoo.run() outputs "foo"
            printFoo.run();
            shouldPrintFoo = false;
            notifyAll();
        }
    }

    public synchronized void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            while (shouldPrintFoo) {
                wait();    
            }
            
            // printBar.run() outputs "bar"
            printBar.run();
            shouldPrintFoo = true;
            notifyAll();
        }
    }
}

方法二:

使用信号量的解决方案

class FooBar {
    private int n;
    Semaphore foo = new Semaphore(1);
    Semaphore bar = new Semaphore(0);

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

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

问题:

  1. 在任何情况下使用一个与另一个可能会导致问题吗?
  2. 在“同步块”和二进制信号量之间做出决定时,我应该考虑或考虑什么?
  3. 有什么我应该遵循的最佳实践吗?任何可以帮助加深我对此知识的参考资料或链接?
4

0 回答 0