阻塞队列实现的生产者消费者模式

    xiaoxiao2021-03-25  85

    public class MyThread {     static int i;     public static void main(String[] args) {         TickOffice t = new TickOffice();         Thread t1 = new Thread(new Produce(t));         t1.setName("售票点1");         t1.start();         Thread t2 = new Thread(new Consumer(t));         t2.setName("售票点2");         t2.start();         Thread t3 = new Thread(new Consumer(t));         t3.setName("售票点3");         t3.start();         Thread t4 = new Thread(new Consumer(t));         t4.setName("售票点4");         t4.start();     } } class TickOffice {     private int ticket = 0;     private ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(15); //存放5张票的阻塞队列     public synchronized void add(){         if(this.queue.size()>=15){             System.out.println("仓库已满");             try {                 this.wait();             } catch (InterruptedException e) {                 e.printStackTrace();             }         }else {             ticket += 1;             try {                 queue.put(ticket);                 Thread.sleep(100);             } catch (InterruptedException e) {                 e.printStackTrace();             }             System.out.println("产生第"+ticket+"张票");             this.notifyAll();         }     }     public synchronized void get(){         if(this.queue.size()<=0){             System.out.println("缺票等待中");             try {                 this.wait();             } catch (InterruptedException e) {                 e.printStackTrace();             }         }else {             System.out.println(Thread.currentThread().getName()+"售出第"+queue.poll()+"张票");             this.notifyAll();         }     } } class Produce implements Runnable{     private TickOffice off;     public Produce(TickOffice off) {         this.off = off;     }     @Override     public void run() {         System.out.println("开张");         while (true) {                          off.add();         }     }      } class Consumer implements Runnable{     private TickOffice off;     public Consumer(TickOffice off) {         this.off = off;     }     @Override     public void run() {         System.out.println("消费者开始取走产品");         while(true){                          off.get();         }     }      }
    转载请注明原文地址: https://ju.6miu.com/read-36254.html

    最新回复(0)