最近和人聊天得知這個經(jīng)常在面試中被問到诸狭,而且說有一定難度,所以自己回來嘗試寫了一下君纫。
基本思路如同阻塞隊列驯遇,同一個鎖,有兩個Condition蓄髓,依次打印叉庐,喚醒對方,阻塞自己釋放鎖会喝。這里有一點(diǎn)要注意的就是 - 先喚醒對方陡叠,再阻塞自己,否則沒有機(jī)會喚醒了肢执。
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();
}
}
}
}