问题描述:
有一家餐馆
餐馆里有三个厨师
一个负责切菜、一个负责炒菜、一个负责端菜
三个厨师出10道菜
顺序必须是:先切再炒再端
这个问题涉及到线程的定制化通讯
线程定制化通讯
public class Cooking {
public String status = "cut";
Lock lock = new ReentrantLock();
Condition cutCondition = lock.newCondition();
Condition cookCondition = lock.newCondition();
Condition giveCondition = lock.newCondition();
public void cut() {
lock.lock();
try {
while (!status.equals("cut")) {
// 不是切菜的时候,等待
try {
cutCondition.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 切菜
System.out.println(Thread.currentThread().getName() + "开始切菜了");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 切完了
status = "cook";
// 交给下一位师傅
cookCondition.signal();
} finally {
lock.unlock();
}
}
public void cook() {
lock.lock();
try {
// 炒菜
while (!status.equals("cook")) {
// 不是炒菜的时候,等待
try {
cookCondition.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 炒菜
System.out.println(Thread.currentThread().getName() + "开始炒菜了");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 炒完了
status = "give";
// 交给下一位师傅
giveCondition.signal();
} finally {
lock.unlock();
}
}
public void give() {
lock.lock();
try {
// 端菜
while (!status.equals("give")) {
// 不是端菜的时候,等待
try {
giveCondition.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 端菜
System.out.println(Thread.currentThread().getName() + "开始端菜了");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 端完了
status = "cut";
// 交给下一位师傅
cutCondition.signal();
} finally {
lock.unlock();
}
}
}
=======================
public class CookingTest {
public static void main(String[] args) {
// 资源
Cooking cooking = new Cooking();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
cooking.cut();
}
}, "切菜师傅").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
cooking.cook();
}
}, "炒菜师傅").start();
new Thread(() -> {
for (int i = 0; i < 10; i++) {
cooking.give();
System.out.println("第"+i+"道菜已经完成。。。。");
}
}, "端菜服务员").start();
}
}