package com.njupt.charapter07;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ABC {
private int times;
private int count=0;
private Lock lock = new ReentrantLock();
private Condition ca = lock.newCondition();
private Condition cb = lock.newCondition();
private Condition cc = lock.newCondition();
public ABC(int times){
this.times=times;
}
public void print(int target , Condition cur,Condition next){
for(int i=0;i<times;i++){
try {
lock.lock();
while(count%3!=target){
cur.await();
}
System.out.println(Thread.currentThread().getName());
count++;
next.signal();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
public void printA(){
print(0,ca,cb);
}
public void printB(){
print(1,cb,cc);
}
public void printC(){
print(2,cc,ca);
}
public static void main(String[] args) {
ABC abc = new ABC(10);
new Thread(()->{
abc.printA();
},"A").start();
new Thread(()->{
abc.printB();
},"B").start();
new Thread(()->{
abc.printC();
},"C").start();
}
}
|