package com.example.app;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.Condition;
public class ThreadTest {
private static Lock lock = new ReentrantLock(true);
private static Condition condition1 = lock.newCondition();
private static Condition condition2 = lock.newCondition();
private static Condition condition3 = lock.newCondition();
private static String str = "A";
public static void main(String[] args) {
Thread t1=new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
printA();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread t2=new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
printB();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
while (true){
try {
printC();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t1.start();
t2.start();
t3.start();
}
public static void printA() throws InterruptedException {
lock.lock();
try{
while(!str.equals("A")){
condition1.await();
}
System.out.println("A");
str = "B";
condition2.signalAll();
}finally {
lock.unlock();
}
}
public static void printB() throws InterruptedException {
lock.lock();
try{
while(!str.equals("B")){
condition2.await();
}
System.out.println("B");
str = "C";
condition3.signalAll();
}finally {
lock.unlock();
}
}
public static void printC() throws InterruptedException {
lock.lock();
try{
while(!str.equals("C")){
condition3.await();
}
System.out.println("C");
str = "A";
condition1.signalAll();
}finally {
lock.unlock();
}
}
}