package org.example.concurrency.test;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author huskyui
*/
@Slf4j
public class Test27 {
static ReentrantLock ROOM = new ReentrantLock();
static boolean hasCigarette = false;
static boolean hasTakeout = false;
static Condition waitCigarette = ROOM.newCondition();
static Condition waitTakeout = ROOM.newCondition();
public static void main(String[] args) {
new Thread(()->{
ROOM.lock();
try {
while (!hasCigarette) {
try {
waitCigarette.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.debug("有烟没{}",hasCigarette);
if (hasCigarette){
log.debug("有烟干活");
}else{
log.debug("没烟不干活");
}
}finally {
ROOM.unlock();
}
}).start();
new Thread(()->{
ROOM.lock();
try{
while (!hasTakeout){
try {
waitTakeout.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.debug("有外卖没{}",hasTakeout);
if (hasTakeout){
log.debug("有外卖干活");
}else{
log.debug("没有外卖,不干活");
}
}finally {
ROOM.unlock();
}
}).start();
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
ROOM.lock();
try {
hasTakeout = true;
waitTakeout.signal();
}finally {
ROOM.unlock();
}
}).start();
new Thread(()->{
ROOM.lock();
try {
hasCigarette = true;
waitCigarette.signal();
}finally {
ROOM.unlock();
}
}).start();
}
}