package com.example.test;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class AirConditioner1{
private Integer number = 1;//1:A 2:B 3:C
private Lock lock = new ReentrantLock();
// 一个门配上三把钥匙
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
public void print5(){
lock.lock();
try{
//1 判断
while(number!=1){
condition1.await(); // this.wait();
}
//2 干活
for(int i = 1;i<=5;i++){
System.out.println(Thread.currentThread().getName()+" "+i);
}
// 3 唤醒
number=2;
condition2.signal();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void print10(){
lock.lock();
try{
//1 判断
while(number!=2){
condition2.await(); // this.wait();
}
//2 干活
for(int i = 1;i<=10;i++){
System.out.println(Thread.currentThread().getName()+" "+i);
}
// 3 唤醒
number=3;
condition3.signal();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void print15(){
lock.lock();
try{
//1 判断
while(number!=3){
condition3.await(); // this.wait();
}
//2 干活
for(int i = 1;i<=15;i++){
System.out.println(Thread.currentThread().getName()+" "+i);
}
// 3 唤醒
number=1;
condition1.signal();
}catch (Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
public class Demo04 {
public static void main(String[] args) {
AirConditioner1 airConditioner1 = new AirConditioner1();
new Thread(()->{
airConditioner1.print5();
},"A").start();
new Thread(()->{
airConditioner1.print10();
},"B").start();
new Thread(()->{
airConditioner1.print15();
},"C").start();
}
}
锁
最新推荐文章于 2024-03-21 10:30:00 发布