Java 线程通信的应用:经典例题:生产者/消费者问题
1 package bytezero.threadcommunication; 2 3 /** 4 * 线程通信的应用:经典例题:生产者/消费者问题 5 * 6 * 7 * 8 * @author Bytezero1·zhenglei! Email:420498246@qq.com 9 * create 2021-10-18 16:10 10 */ 11 12 //店员 13 class Clerk{ 14 15 private int productCount = 0; 16 //生产产品 17 public synchronized void produceProduct() { 18 19 if(productCount < 20){ 20 productCount++; 21 System.out.println(Thread.currentThread().getName() +":开始生产第"+productCount+"个产品"); 22 23 notify(); //唤醒消费者 24 25 }else{ 26 //等待 27 try { 28 wait(); 29 } catch (InterruptedException e) { 30 e.printStackTrace(); 31 } 32 } 33 34 } 35 36 //消费产品 37 public synchronized void consumerProduct() { 38 if(productCount > 0){ 39 System.out.println(Thread.currentThread().getName()+":开始消费第"+productCount+"个产品"); 40 productCount--; 41 42 notify();//唤醒生产者 43 44 }else{ 45 //等待 46 try { 47 wait(); 48 } catch (InterruptedException e) { 49 e.printStackTrace(); 50 } 51 } 52 } 53 } 54 55 //生产者 56 class Producer extends Thread { 57 private Clerk clerk; 58 59 public Producer(Clerk clerk) { 60 this.clerk = clerk; 61 } 62 63 @Override 64 public void run() { 65 System.out.println(Thread.currentThread().getName() +":开始生产产品...."); 66 67 while (true){ 68 try { 69 Thread.sleep(10); 70 } catch (InterruptedException e) { 71 e.printStackTrace(); 72 } 73 clerk.produceProduct(); 74 } 75 76 } 77 } 78 79 //消费者 80 class Consumer extends Thread{ 81 private Clerk clerk; 82 83 public Consumer(Clerk clerk) { 84 this.clerk = clerk; 85 } 86 87 @Override 88 public void run() { 89 System.out.println(Thread.currentThread().getName() +":开始消费产品...."); 90 91 while (true){ 92 try { 93 Thread.sleep(20); 94 } catch (InterruptedException e) { 95 e.printStackTrace(); 96 } 97 clerk.consumerProduct(); 98 } 99 } 100 101 } 102 public class ProductTest { 103 public static void main(String[] args) { 104 Clerk clerk = new Clerk(); 105 106 Producer p1 = new Producer(clerk); 107 p1.setName("生产者1"); 108 109 Consumer c1 = new Consumer(clerk); 110 c1.setName("消费者1"); 111 112 Consumer c2 = new Consumer(clerk); 113 c2.setName("消费者2"); 114 115 p1.start(); 116 c1.start(); 117 c2.start(); 118 119 } 120 }
........
本文来自博客园,作者:Bytezero!,转载请注明原文链接:https://www.cnblogs.com/Bytezero/p/15421183.html