美文网首页
1115. 交替打印FooBar

1115. 交替打印FooBar

作者: 上杉丶零 | 来源:发表于2020-03-19 14:26 被阅读0次
    class FooBar {
        private int n;
        private Semaphore foo = new Semaphore(1);
        private 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() outputs "foo". Do not change or remove this line.
                printFoo.run();
                bar.release();
            }
        }
    
        public void bar(Runnable printBar) throws InterruptedException {
            for (int i = 0; i < n; i++) {
                bar.acquire();
    
                // printBar.run() outputs "bar". Do not change or remove this line.
                printBar.run();
                foo.release();
            }
        }
    }
    
    image.png

    相关文章

      网友评论

          本文标题:1115. 交替打印FooBar

          本文链接:https://www.haomeiwen.com/subject/quclyhtx.html