生产者-消费者

在学习java 的多线程中,生产者和消费者的问题是最经典的问题,因此在学习了java的多线程后
本文假设的是只有一个篮子、一个生产者和消费者

首先需要创建一个类Apple(苹果)的类,这个类是产品。

//创建一个苹果类,作为产品
public class Apple{
    private int i;
    public Apple(int i){
        this.i=i;
    }
    public String toString(){
        return "苹果"+i;
    }
}

创建一个篮子,其中有装入的方法和取出的方法,都是synchronized的方法,使用synchronized的原因是,不管生产者和消费者都是从一个篮子里来取苹果的,为了避免冲突,采用同步的策略。

//创建一个篮子装苹果
public class Basket{
    private Apple[] apples=new Apple[5];
    private int index=0;//用来标记篮子里还有多少个Appple

    public synchronized void push(Apple apple){
        while(index==apples.length){
            try {
                    this.wait();
            } catch (InterruptedException e) {
                    e.printStackTrace();
            }
        }
        this.notify();
        index++;
        apples[index]=apple;    
    } 

    public synchronized Apple pop(){
        while(index==0){
            try {
                    this.wait();
            } catch (InterruptedException e) {
                    e.printStackTrace();
            }
        }
        index--;
        return apples[index];
    }
}

下面是生产者和消费者类

public class Producer implements Runnable{

    private Basket basket;
    public Producer(Basket basket){
        this.basket=basket;
    }
    @Override
    public void run() {
        for(int i=0;i<20;i++){
            Apple apple = new Apple(i);
            basket.push(apple);
            System.out.println("生产了"+apple);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class Consumer implements Runnable{
    private Basket basket;//容器
    public Consumer(Basket basket){
        this.basket=basket;
    }
    @Override
    public void run() {
        for(int i=0;i<20;i++){
            Apple apple=basket.pop();
            System.out.println("消费了"+apple);
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }       
    }
}

测试类Main

public class Main {
    public static void main(String[] args){
        Basket basket=new Basket();//容器
        Producer producer=new Producer(basket);//生产者
        Consumer consumer=new Consumer(basket);//消费者
        Thread thread1=new Thread(producer);
        Thread thread2=new Thread(consumer);
        thread1.start();
        thread2.start();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值