JAVA多线程等待唤醒案例:一个厨师一个服务员十份菜问题

JAVA多线程等待唤醒案例:一个厨师一个服务员十份菜问题,第1张

JAVA多线程等待唤醒案例:一个厨师一个服务员十份菜问题

案例:有家餐馆的取餐口只能放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();
            }
        }
    }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5611720.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存