生产者-消费者线程模式

用队列实现的一个简单的生产者消费者模式,代码如下:

import java.util.LinkedList;
import java.util.Random;

//消费者线程
class A extends Thread{
    private  LinkedList<Integer> queue;   //用一个队列表示商品缓冲区
    public A(LinkedList<Integer> queue){
        this.queue=queue;
    }
    public void run(){
        while(true){
            synchronized(queue) {  //获得queue锁的线程才能继续执行
                if(queue.size()==0){  //缓冲区没有商品
                    try {
                        queue.wait();  //线程等待,wait方法会释放锁
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print("消费者线程消费:"+queue.poll()+"  目前剩余:");
                for(int x:queue)
                    System.out.print(x+" ");
                System.out.println();
                queue.notifyAll();  //消费了一个商品,发出通知,表示缓冲区不满,生产者线程可以继续生产
                try {
                    Thread.sleep(500);  //避免输出过快
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
//生产者线程
class B extends Thread{
    private final LinkedList<Integer> queue;
    public B(LinkedList<Integer> queue){
        this.queue=queue;
    }
    public void run(){
        while(true){
            synchronized(queue) {
                if(queue.size()>=5){  //这里设置的缓冲区最大容量是5
                    try {
                        queue.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                int x=new Random().nextInt(100);
                queue.offer(x);
                System.out.print("生产者线程生产:"+x+"  目前剩余:");
                for(int y:queue)
                    System.out.print(y+" ");
                System.out.println();

                queue.notifyAll();  //通知
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

public class Main {
    public static void main(String[] args) {
        LinkedList<Integer> queue=new LinkedList<>();
        new A(queue).start();
        new B(queue).start();
    }
}

运行结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值