package com.orderPC;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 执行A,然后B,然后C,然后A
*/
public class ProductC {
public static void main(String[] args) {
Data3 data3 = new Data3();
new Thread(()->{
for (int i = 0; i <5 ; i++) {
data3.printA();
}
},"A").start();
new Thread(()->{
for (int i = 0; i < 5; i++) {
data3.printB();
}
},"B").start();
new Thread(()->{
for (int i = 0; i < 5; i++) {
data3.printC();
}
},"C").start();
}
}
//资源类
class Data3{
private Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();
private int num = 1;
public void printA(){
lock.lock();
try {
while(num != 1){
//等待
condition1.await();
}
System.out.println(Thread.currentThread().getName()+"-->AAA");
num=2;
//唤醒,唤醒指定的
condition2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printB(){
lock.lock();
try {
while(num !=2 ){
condition2.await();
}
System.out.println(Thread.currentThread().getName()+"-->BBB");
num =3;
//唤醒指定线程
condition3.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printC(){
lock.lock();
try {
while(num != 3){
//等待
condition3.await();
}
System.out.println(Thread.currentThread().getName()+"-->CCC");
num = 1;
condition1.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}