2020年9月12日 生產者與消費者問題
阿新 • • 發佈:2020-09-12
package com.guigu.test14; public class Test14 { public static void main(String[] args) { FoodTable f = new FoodTable(); Cook c = new Cook("廚子",f); Waiter w = new Waiter("服務員", f); c.start(); w.start(); } } class FoodTable{ private static finalint MAX = 3; private int count; public synchronized void put(){ if(count>=MAX){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } count++; System.out.println(Thread.currentThread().getName()+"放了一盤菜,剩餘:" + count); this.notify(); } public synchronized void take(){ if(count<=0){ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } count--; System.out.println(Thread.currentThread().getName()+"取走一盤菜,剩餘:" + count); this.notify(); } } class Cook extends Thread{ private FoodTable f; public Cook(String name, FoodTable f) { super(name); this.f = f; } @Override public void run() { while(true){ f.put(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } class Waiter extends Thread{ private FoodTable f; public Waiter(String name, FoodTable f) { super(name); this.f = f; } @Override public void run() { while(true){ f.take(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }