package exer4; /** * @author 高槐玉 * #Description 生产者,消费者案例 * #Date: 2022/10/9/14点08分 * #Shangguigu: */ class Clerk{ private int goods = 0; //生产货物; public synchronized void createProduct() { if (goods < 20) { goods++; System.out.println(Thread.currentThread().getName() + "生产第:" + goods + "货物"); notify(); }else{ try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } public synchronized void consumerProduct() { if (goods > 0) { System.out.println(Thread.currentThread().getName() + "消费第:" + goods + "货物"); goods--; notify(); }else { //等待 try { wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } class Producer extends Thread{ private Clerk clerk; public Producer(Clerk clerk){ this.clerk = clerk; } public void run(){ System.out.println(getName() + ":开始生产产品...."); while (true) { try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } clerk.createProduct(); } } } class Consumer extends Thread{ private Clerk clerk; public Consumer(Clerk clerk){ this.clerk = clerk; } public void run(){ System.out.println(getName() + ":开始消费产品..."); while (true) { try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } clerk.consumerProduct(); } } } public class Product { public static void main(String[] args) { Clerk c =new Clerk(); Producer p1 = new Producer(c); Consumer c1 = new Consumer(c); p1.setName("生产者"); c1.setName("消费者"); p1.start(); c1.start(); } }
标签:goods,Thread,Clerk,--,clerk,练习,线程,void,public From: https://www.cnblogs.com/gaohuaiyu/p/16772676.html