最近和人聊天得知这个经常在面试中被问到,而且说有一定难度,所以自己回来尝试写了一下。
基本思路如同阻塞队列,同一个锁,有两个Condition,依次打印,唤醒对方,阻塞自己释放锁。这里有一点要注意的就是 - 先唤醒对方,再阻塞自己,否则没有机会唤醒了。
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class PrintInTurn {
ReentrantLock lock = new ReentrantLock();
Condition thisPrintcondition = lock.newCondition();
Condition otherPrintcondition = lock.newCondition();
public static void main(String[] args) {
(new PrintInTurn()).start();
}
public void start() {
PrintThread p1 = new PrintThread(lock, thisPrintcondition, otherPrintcondition);
PrintThread p2 = new PrintThread(lock, otherPrintcondition, thisPrintcondition);
(new Thread(p1)).start();
(new Thread(p2)).start();
}
class PrintThread implements Runnable {
ReentrantLock lock;
Condition thisPrintcondition;
Condition otherPrintcondition;
public PrintThread(ReentrantLock lock, Condition thisPrintcondition, Condition otherPrintcondition) {
this.lock = lock;
this.thisPrintcondition = thisPrintcondition;
this.otherPrintcondition = otherPrintcondition;
}
@Override
public void run() {
try {
lock.lock();
while(true) {
System.out.println(Thread.currentThread().getName());
otherPrintcondition.signal();
thisPrintcondition.await();
}
}catch(Exception e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
}