案例:有家餐馆的取餐口只能放10份快餐,厨师做完快餐放在取餐口,服务员从这个取餐口取出快餐。现在有1个厨师和1个服务员。且服务员不是等到10份餐放满才取菜,厨师不是等到10份菜都取完才做菜。
package ThreadMessage;
public class Practice {
public static void main(String[] args) {
RestaurantThread waiterThread = new WaiterThread();
RestaurantThread cookThread = new CookThread();
Thread waiter = new Thread(waiterThread, "服务员");
Thread cook = new Thread(cookThread, "厨师");
waiter.start();
cook.start();
}
}
class RestaurantThread implements Runnable {
static int count = 0;
static Object obj = new Object();
static Object obj2 = new Object();
@Override
public void run() {
}
}
class WaiterThread extends RestaurantThread {
public void take() {
while (count >= 1) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj2) {
System.out.println("服务员来取第" + count + "份餐了");
count--;
}
synchronized (obj) {
obj.notify();
}
}
}
@Override
public void run() {
while (true) {
if (count == 0) {
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
take();
}
}
}
}
class CookThread extends RestaurantThread {
public void cook() {
while (count < 10) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj2) {
System.out.println("厨师正在做第" + (count + 1) + "份餐");
count++;
}
synchronized (obj) {
obj.notify();
}
}
}
@Override
public void run() {
while (true) {
if (count == 10) {
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
if (count != 10) {
cook();
}
}
}
}