【Leetcode】1115. Print FooBar Alternately

题目地址:

https://leetcode.com/problems/print-foobar-alternately/

要求设计多线程的程序,使得两个线程可以交替打印"foo""bar"两个单词,各 n n n次。

可以将打印的部分加锁,设置一个变量,其为true时打印foo,其为false时打印bar。打印完之后取反。在打印foo的程序里如果发现这个变量为false,则进入wait,让出同步锁给另一个线程打印。代码如下:

public class FooBar {
    
    private int n;
    private boolean runFoo;
    
    public FooBar(int n) {
        this.n = n;
        runFoo = true;
    }
    
    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            synchronized (this) {
                // 如果runFoo是false,当前线程进入等待,让出锁,给bar函数打印bar
                while (!runFoo) {
                    wait();
                }
                
                // printFoo.run() outputs "foo". Do not change or remove this line.
                printFoo.run();
                runFoo = false;
                notify();
            }
        }
    }
    
    public void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            synchronized (this) {
                // wait until foo() is running
                while (runFoo) {
                    wait();
                }
                
                // printBar.run() outputs "bar". Do not change or remove this line.
                printBar.run();
                runFoo = true;
                notify();
            }
        }
    }
}
上一篇:动态代理


下一篇:go模式-责任链