Leetcode multi thread alternate printing foobar

Time:2020-9-22

order

This article mainly records the alternate printing foobar of leetcode multithreading

subject

We provide a class:

class FooBar {
  public void foo() {
    for (int i = 0; i < n; i++) {
      print("foo");
    }
  }

  public void bar() {
    for (int i = 0; i < n; i++) {
      print("bar");
    }
  }
}

Two different threads will share a foobar instance. One thread will call the foo () method and the other will call the bar () method.

Please design modification program to ensure that "foobar" is output n times.

Source: leetcode
Link: https://leetcode-cn.com/problems/print-foobar-alternately
The copyright belongs to the network. Commercial reprint please contact the official authorization, non-commercial reprint please indicate the source.

Explanation

class FooBar {
    private int n;

    ReentrantLock lock = new ReentrantLock();
    Condition fooCnd = lock.newCondition();
    Condition barCnd = lock.newCondition();

    boolean foo = true;

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

    public void foo(Runnable printFoo) throws InterruptedException {
        
        lock.lock();
        try {
            for (int i = 0; i < n; i++) {
                if (!foo) {
                    fooCnd.await();
                }
                foo = false;
                // printFoo.run() outputs "foo". Do not change or remove this line.
                printFoo.run();
                barCnd.signal();
            }
        } finally {
            lock.unlock();
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {
        
        lock.lock();
        try {
            for (int i = 0; i < n; i++) {
                if (foo) {
                    barCnd.await();
                }
                foo = true;
                // printBar.run() outputs "bar". Do not change or remove this line.
                printBar.run();
                fooCnd.signal();
            }
        } finally {
            lock.unlock();
        }
    }
}
  • Here, the condition of reentrantlock is used to control the condition

Summary

Because it is necessary to print repeatedly, the condition of reentrantlock is selected to control the condition

doc

  • print-foobar-alternately