多线程中的生产者消费者案例

Posted 技术很low的瓜贼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多线程中的生产者消费者案例相关的知识,希望对你有一定的参考价值。

生产者消费者

Object类常用的方法

方法功能
void wait()用于使得线程进入等待状态,直到其它线程调用notify()或notifyAll()方法
void wait(long timeout)用于进入等待状态,直到其它线程调用方法或参数指定的毫秒数已经过去为止
void notify()用于唤醒等待的单个线程
void notifyAll()用于唤醒等待的所有线程

案例描述

在一个固定大小的仓库中存放物品,当仓库不为满的时候,生产者生产,同时消费者还在消费,实现同步机制

  • 仓库代码:
package 线程.ProduceAndConsumer;

public class StoreHouse 

    private int cnt = 0; // 描述商品数量

    public synchronized void produceProduct() 
        notify();
        if (cnt < 10) 
            System.out.println("线程" + Thread.currentThread().getName() + "正在生产第" + (cnt + 1) + "个商品");
            cnt ++;
         else 
            try 
                wait();
             catch (InterruptedException e) 
                e.printStackTrace();
            
        
    

    public synchronized void produceConsumer() 
        notify();
        if (cnt > 0) 
            System.out.println("线程" + Thread.currentThread().getName() + "正在消费第" + cnt + "个商品");
            cnt --;
         else 
            try 
                wait();
             catch (InterruptedException e) 
                e.printStackTrace();
            
        
    


  • 生产者代码:
package 线程.ProduceAndConsumer;

public class ProduceThread implements Runnable


    // 声明一个仓库类型的引用作为成员变量,为了能够调用仓库类中的方法 合成服用原则
    private StoreHouse storeHouse;

    public ProduceThread() 
    

    public ProduceThread(StoreHouse storeHouse) 
        this.storeHouse = storeHouse;
    

    @Override
    public void run() 
        while (true) 
            storeHouse.produceProduct();
            try 
                Thread.sleep(100);
             catch (InterruptedException e) 
                e.printStackTrace();
            
        

    


  • 消费者代码:
package 线程.ProduceAndConsumer;

public class ConsumerThread implements Runnable

    private StoreHouse storeHouse;

    public ConsumerThread() 
    

    public ConsumerThread(StoreHouse storeHouse) 
        this.storeHouse = storeHouse;
    

    @Override
    public void run() 
        while (true) 
            storeHouse.produceConsumer();
            try 
                Thread.sleep(1000);
             catch (InterruptedException e) 
                e.printStackTrace();
            
        
    


  • 实现类代码:
package 线程.ProduceAndConsumer;

public class Test 

    public static void main(String[] args) 
        StoreHouse storeHouse = new StoreHouse();

        ProduceThread produceThread = new ProduceThread(storeHouse);

        ConsumerThread consumerThread = new ConsumerThread(storeHouse);

        Thread t1 = new Thread(produceThread);
        Thread t2 = new Thread(consumerThread);

        t1.start();
        t2.start();
    


以上是关于多线程中的生产者消费者案例的主要内容,如果未能解决你的问题,请参考以下文章

Java多线程与并发——生产者与消费者应用案例

多线程四大经典案例及java多线程的实现

多线程生产者消费者案例

java多线程 生产者消费者案例-虚假唤醒

多线程案例-阻塞式队列

多线程四大经典案例