public class MutiPrintABC {
private Lock lock=new ReentrantLock();
private Condition condition1=lock.newCondition();
private Condition condition2=lock.newCondition();
private Condition condition3=lock.newCondition();
private int number=1;
public void printA() throws InterruptedException {
lock.lock();
try {
while (number!=1){
condition1.await();
}
System.out.println("A");
number=2;
condition2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void printB() throws InterruptedException {
lock.lock();
try {
while (number!=2){
condition2.await();
}
System.out.println("B");
number=3;
condition3.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void printC() throws InterruptedException {
lock.lock();
try {
while (number!=3){
condition3.await();
}
System.out.println("C");
number=1;
condition1.signal();
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public class MutiPrintABC {
int number=1;
public synchronized void printA() throws InterruptedException {
while (number!=1){
this.wait();
}
number=2;
System.out.println("A");
this.notifyAll();
}
public synchronized void printB() throws InterruptedException {
while (number!=2){
this.wait();
}
number=3;
System.out.println("B");
this.notifyAll();
}
public synchronized void printC() throws InterruptedException {
while (number!=3){
this.wait();
}
number=1;
System.out.println("C");
this.notifyAll();
}
}
public class MutiPrintABCMain {
public static void main(String[] args) {
MutiPrintABC printABC=new MutiPrintABC();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++){
try {
printABC.printA();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++){
try {
printABC.printB();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<10;i++){
try {
printABC.printC();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
}