Java经典多线程问题--生产者与消费者

今天研究了一下Java多线程,顺便写了一下多线程中的经典问题—–生产者消费者经典问题,推荐一个线程链接Java基础知识回顾–线程
这个里面其实写了生产者与消费者问题,估计在后面大家看起来比较费劲,所以我提取出来再讲解一遍。

package yanning;

public class ProducerConsumer {

    public static void main(String[] args) {
        Tong tong = new Tong();
        Producer p = new Producer(tong);
        Consumer c = new Consumer(tong);
        new Thread(p).start();
        new Thread(c).start();
    }
}
class Baozi {
    int id;
    Baozi(int id) {
        this.id = id;
    }
    public String toString() {
        return "Baozi:" + id;
    }
}
class Tong {
    int index;
    Baozi[] BZ = new Baozi[10];

    public synchronized void push(Baozi baozi) {
        if(index == BZ.length) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.notify();
        BZ[index] = baozi;
        index ++;
    }
    public synchronized Baozi pop() {
        if(index == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        this.notify();
        index --;
        return BZ[index];
    }
}

class Producer implements Runnable{
    Tong tong = null;
    Producer(Tong tong) {
        this.tong = tong;
    }

    public void run() {
        for( int i = 0; i < 10; i ++ ) {
            Baozi baozi = new Baozi( i );
            tong.push(baozi);
        System.out.println("生产了 :" + baozi);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }
    }
}

class Consumer implements Runnable{
    Tong tong = null;
    Consumer(Tong tong) {
        this.tong = tong;
    }

    public void run() {
        for( int i = 0; i < 10; i ++ ) {
            Baozi baozi = tong.pop();
            System.out.println("消费了:" + baozi);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }   
}

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值