Java 线程通信模型小案例
package com.zhong.thread.usethread;import java.util.ArrayList;
import java.util.List;
public class CookAndFood {public static void main(String[] args) {Desk desk = new Desk();new Thread(() -> {while (true) {desk.put();}}, "厨师1").start();new Thread(() -> {while (true) {desk.put();}}, "厨师2").start();new Thread(() -> {while (true) {desk.put();}}, "厨师3").start();new Thread(() -> {while (true) {desk.get();}}, "顾客1").start();new Thread(() -> {while (true) {desk.get();}}, "顾客2").start();}
}class Desk extends Thread {private List<String> desk = new ArrayList<>();public synchronized void put() {try {String name = Thread.currentThread().getName();if (desk.isEmpty()) {desk.add(name + "做得的包子");System.out.println(name + "做了一个包子");Thread.sleep(2000);this.notifyAll();this.wait();} else {this.notifyAll();this.wait();}} catch (InterruptedException e) {throw new RuntimeException(e);}}public synchronized void get() {try {String name = Thread.currentThread().getName();if (desk.size() == 1) {System.out.println(name + " 吃了包子 " + desk.get(0));desk.clear();Thread.sleep(1000);this.notifyAll();this.wait();} else {this.notifyAll();this.wait();}} catch (Exception e) {throw new RuntimeException(e);}}
}