使用线程实现多生产者,多消费者demo
1 package com.woniuxy.test2; 2 3 import java.util.Arrays; 4 5 /** 6 * @author wuwenjun 7 * @time 2020/11/12/21:07:41 8 */ 9 // 10 class Product{ 11 private String[] strs = "☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆ ☆".split(" "); 12 13 private int i; 14 15 public void put(){//加锁,防止放入时被抢走。 16 synchronized (this) { 17 while(i==strs.length){//当为最大时等待 18 try { 19 this.wait(); 20 } catch (InterruptedException e) { 21 e.printStackTrace(); 22 } 23 } 24 25 strs[i++] = "★"; 26 System.out.println(Thread.currentThread().getName()+"放入:"+this); 27 this.notifyAll();//只要放入后就唤醒其它线程 28 } 29 } 30 31 public void get(){//加锁,防止取出时被被抢走中断。 32 synchronized (this) { 33 while(i==0){//当没有星星时,就等待 34 try { 35 this.wait(); 36 } catch (InterruptedException e) { 37 e.printStackTrace(); 38 } 39 } 40 //星星-1 41 strs[--i] = "☆"; 42 System.out.println(Thread.currentThread().getName()+"取出:"+this); 43 this.notifyAll();//只要取出后,就唤醒其它线程 44 } 45 } 46 47 @Override 48 public String toString() { 49 return Arrays.toString(strs); 50 } 51 } 52 53 class Shop implements Runnable{ 54 55 private Product product; 56 57 public Shop(Product product) { 58 this.product = product; 59 } 60 61 @Override 62 public void run() { 63 synchronized (this) { 64 while (true) {//不断的取 65 product.put(); 66 } 67 } 68 } 69 } 70 71 class Consumer implements Runnable{ 72 73 private Product product; 74 75 public Consumer(Product product) { 76 this.product = product; 77 } 78 79 @Override 80 public void run() { 81 82 synchronized (this) { 83 while (true) { 84 product.get(); 85 } 86 } 87 } 88 } 89 90 91 public class ShopConsumer { 92 public static void main(String[] args) { 93 Product product = new Product();//共用的第三方对象 94 95 Shop shop = new Shop(product); 96 Consumer consumer = new Consumer(product); 97 98 Thread th = new Thread(shop,"商家1"); 99 Thread th2 = new Thread(consumer,"用户1"); 100 Thread th3 = new Thread(shop,"商家2"); 101 Thread th4 = new Thread(consumer,"用户2"); 102 103 th.start(); 104 th2.start(); 105 th3.start(); 106 th4.start(); 107 108 } 109 }