最近研究了一些多线程中并行处理,串行输出的题。总结了几种方法。
这种题的内容一般是:k 个线程,分别能够输出"A"、“B”、“C”…,按照"A"、“B”、“C”…的顺序输出 N 次。
以 LeetCode 上的1115. 交替打印FooBar 为例。
方法一:synchronized
class FooBar {
private int n;
int flag = 0;
public FooBar(int n) {
this.n = n;
}
public synchronized void foo(Runnable printFoo) throws InterruptedException {
for (int i = 0; i < n; i++) {
while(flag != 0){
this.wait();
}
printFoo.run();
flag = 1;
this.notifyAll();
}
}
public synchronized void bar(Runnable printBar) throws InterruptedException {
for (int i = 0; i < n; i++) {
while(flag != 1){
this.wait();
}
printBar.run();
flag = 0;
this.notifyAll();
}
}
}
方法二:Condition
class FooBar {
private int n;
private ReentrantLock lock = new ReentrantLock();
private Condition fooCondition = lock.newCondition();
private Condition barCondition = lock.newCondition();
private int flag = 0;
public FooBar(int n)<