sequence
This article mainly records leetcode multi-threaded alternate printing FooBar
The title
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 one instance of FooBar. One thread will call the foo() method and the other thread will call the bar() method. Please design the modification program to ensure that "foobar" is printed n times. Source: LeetCode Link: https://leetcode-cn.com/problems/print-foobar-alternately Copyright belongs to The Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.Copy the code
Answer key
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(); }}}Copy the code
- The condition of ReentrantLock is used here for condition control
summary
Because the print loop is repeated multiple times, ReentrantLock’s condition is chosen for condition control
doc
- print-foobar-alternately