线程安全(线程同步)案例2:生产者消费者问题

模拟生产者——消费者问题

生产者类:



public class Producer implements Runnable{
    private Pool pool; //产品池

    public Producer(Pool pool) {
        this.pool = pool;
    }

    @Override
    public void run() {
    for(int i = 0;i < 10; i++){
        //产生一个产品需要500ms
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String d = "产品"+i;
        System.out.println("生产:"+d);
        //将产品存放到产品池中
        pool.put(d);
    }
    }
}

产品池类

package day6.producer;

import java.util.Arrays;

public class Pool {
    private int capacity;//定义产品池容量
    private int size = 0; //记录当前产品数
    private String[] data; //存放产品
    private int index1 = 0; //生产者,是下标,环装存储
    private int index2 = 0; //消费者
    //构造函数
    public Pool(int capacity){
        this.capacity = capacity;
        data=new String[capacity];
        Arrays.fill(data,"无");
    }
    //存放产品
    public synchronized void put(String d){
        if(size ==capacity-1){ //如果容量满了,则让调用该线程的方法阻塞
            try {
                this.wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        data[index1] =d; //size 有空间,则存放产品
        index1=(index1 + 1) % capacity; //实现环状存储
        size++;
        //当有产品时,唤醒休眠的线程
        this.notify();
    }
    //取产品
    public synchronized String get(){
        if(size == 0){ //判断是否有产品可以拿出,没有产品则调用该方法的线程休眠
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        String d = data[index2];
        index2 = (index2 +1) % capacity;  //绕圈
        size--;
        this.notify();//叫醒生产者,可以生产
        return d;
    }
}

消费者类



public class Customer implements Runnable{
    private Pool pool; //产品池

    public Customer(Pool pool) {
        this.pool = pool;
    }
    @Override
    public void run() {
        for(int i = 0;i < 10;i++){//取十次产品
            String d = pool.get();//从产品池中取出产品
            System.out.println("消费:"+d);
            try {
                Thread.sleep( 500 ); //取一个产品要500ms
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Main类



public class Main {
    public static void main(String[] args) {
        Pool pool = new Pool( 3 ); //产品池,容量为3
        Thread producer = new Thread( new Producer( pool ) );//生产者
        Thread customer = new Thread( new Customer( pool ) );//消费者

        producer.start();
        customer.start();
    }
}

 

你可能感兴趣的:(Java基础)