JUC生产者消费者指定唤醒
JUC生产者消费者指定唤醒
使用不同的condition,调用signal()
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Demo {
public static void main(String[] args) {
Data data = new Data();
// 线程A
new Thread(() -> { for (int i = 0; i < 10; ++i) data.printA();}).start();
// 线程B
new Thread(() -> { for (int i = 0; i < 10; ++i) data.printB();}).start();
// 线程C
new Thread(() -> { for (int i = 0; i < 10; ++i) data.printC();}).start();
}
}
// 资源类
class Data {
// Lock对象
private Lock lock = new ReentrantLock();
// 监视器
private final Condition conditionA = lock.newCondition();
private final Condition conditionB = lock.newCondition();
private final Condition conditionC = lock.newCondition();
// 条件
private int num = 0;
// 当num==0时执行A
// 当num==1时执行B
// 当num==2时执行C
// 方法A
public void printA(){
// 上锁
lock.lock();
try {
// 等待
while (num != 0){
conditionA.await();
}
// 业务
System.out.println("A");
// 通知B
num = 1;
conditionB.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 解锁
lock.unlock();
}
}
// 方法B
public void printB(){
// 上锁
lock.lock();
try {
// 等待
while (num != 1){
conditionB.await();
}
// 业务
System.out.println("B");
// 通知C
num = 2;
conditionC.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 解锁
lock.unlock();
}
}
// 方法C
public void printC(){
// 上锁
lock.lock();
try {
// 等待
while (num != 2){
conditionC.await();
}
// 业务
System.out.println("C");
// 通知A
num = 0;
conditionA.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 解锁
lock.unlock();
}
}
}