厨师 public class Cook extends Thread{ @Override public void run() { while(true){ synchronized (Desk.lock) { if (Desk.count==0){ break; }else { if (Desk.foodFlag==1){ try { Desk.lock.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } }else { System.out.println("厨师做了一碗面条"); //面条加1 Desk.foodFlag=1; //打开睡眠 Desk.lock.notifyAll(); } } } } } }
面条
public class Foodie extends Thread { /* 1.循环 2.同步代码块 3.判断是否到末尾 4.没有到末尾进行执行核心 */ @Override public void run() { while (true) { //进行上锁 synchronized (Desk.lock) { //判断是否吃完 if (Desk.count == 0) { break; } else { //判断是否有面条 if (Desk.foodFlag == 0) { try { Desk.lock.wait(); } catch (InterruptedException e) { throw new RuntimeException(e); } //有面条 //吃的碗减一 } else { Desk.count--; System.out.println("吃货在吃面条还能吃" + Desk.count + "晚"); //吃完唤醒厨师做饭 Desk.lock.notifyAll(); //修改桌子状态 Desk.foodFlag = 0; } } } } } }
创建对象
public class Desk { //判断是否有面条 public static int foodFlag=0; //总数 public static int count=10; //锁对象 public static Object lock = new Object(); }
程序主入口
public class ThreadDeno { public static void main(String[] args) { //创建线程对象 Cook c = new Cook(); Foodie f = new Foodie(); //设置名字 c.setName("厨师"); f.setName("吃货"); c.start(); f.start(); } }标签:面条,lock,唤醒,foodFlag,Desk,new,机制,等待,public From: https://blog.csdn.net/2401_84239732/article/details/140187375