注意!! notify和wait 使用后续补充
package com.qey.learn;/*** @ClassName Water* @Description* @Author qianxl* @Date 2021-03-01 23:09* @Version 1.1**/
public class Water {// 服务员来提供产品的输入的输出private int product;public Water(int maxSize) {this.product = maxSize;}public int products() {synchronized (this) {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}if (product >= 20) {System.out.println("已经生成满了");} else {product++;System.out.println(Thread.currentThread().getName()+"成功添加:" + product);}}return product;}public int consumers() {synchronized (this) {try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}if (product <= 0) {System.out.println("产品已经消费完了");} else {product--;System.out.println(Thread.currentThread().getName()+"成功消费" + product);}}return product;}public static void main(String[] args) {Water water = new Water(20);Thread t1 = new Thread(new Product(water));Thread t2 = new Thread(new Consumer(water));Thread t3 = new Thread(new Product(water));Thread t4 = new Thread(new Consumer(water));t1.start();t2.start();t3.start();t4.start();}}class Product implements Runnable {public Water t;public Product(Water t) {this.t = t;}@Overridepublic void run() {while (true) {t.products();}}
}class Consumer implements Runnable {public Water t;public Consumer(Water t) {this.t = t;}@Overridepublic void run() {while (true) {t.consumers();}}
}