java 之 手写 生产者-消费者

本文探讨了Java中如何手写实现生产者-消费者模式,重点涉及数据结构消息队列以及多线程的生产与消费操作。

主要考点:

            数据结构:消息队列;

            多线程生产,多线程消费;

 

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * class ConsumerAndProducer
 *
 * @author lonkin created on 2019-09-23
 */

public class ConsumerAndProducer {

    public static void main(String[] args) {

        //内存缓冲区
        BlockingQueue<Data> queue = new LinkedBlockingQueue<>(10);
        //生产者
        Provider p1 = new Provider(queue);
        Provider p2 = new Provider(queue);
        Provider p3 = new Provider(queue);
        //消费者
        Consumer c1 = new Consumer(queue);
        Consumer c2 = new Consumer(queue);
        Consumer c3 = new Consumer(queue);
        //创建线程池,这是一个缓存的线程池,可以创建无穷大的线程,没有任务的时候不创建线程,空闲线程存活的时间为60s。
        ExecutorService cachepool = Executors.newCachedThreadPool();
        cachepool.execute(p1);
        cachepool.execute(p2);
        cachepool.execute(p3);
        cachepool.execute(c1);
        cachepool.execute(c2);
        cachepool.execute(c3);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        p1.stop();
        p2.stop();
        p3.stop();
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static class Data {
        private String id;

        private String name;

        public Data(String id,String name){
            this.id = id;
            this.name = name;
        }
        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Data [id=" + id + ", name=" + name + "]";
        }
    }

    public static class Provider implements Runnable{
        //共享缓冲区
        private BlockingQueue<Data> queue;
        //多线程间是否启动变量,有强制从主内存中刷新的功能,及时返回线程状态
        private volatile boolean isRunning = true;
        //id生成器
        private static AtomicInteger count = new AtomicInteger();

        public Provider(BlockingQueue queue){
            this.queue = queue;
        }

        @Override
        public void run() {
            while(isRunning){
                //随机休眠0-1000毫秒 表示获取数据
                try {
                    Thread.sleep(1000);
                    //获取的数据进行累计
                    int id  = count.incrementAndGet();
                    //比如通过一个getData()方法获取了
                    Data data = new Data(Integer.toString(id),"数据"+id);
                    System.out.println("当前生产者线程:"+ Thread.currentThread().getName() + ",获取了数据,id为:"+ id+ ",进行装载到公共缓冲区中。。。");
                    if(!this.queue.offer(data,2, TimeUnit.SECONDS)){
                        System.out.print("提交缓冲区数据失败");
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        public void  stop(){
            this.isRunning = false;
        }
    }

    public static class Consumer implements Runnable {

        private BlockingQueue<Data> queue;

        public Consumer(BlockingQueue queu){
            this.queue = queu;
        }

        @Override
        public void run() {
            while(true){
                try{
                    //获取数据
                    Data data = this.queue.take();
                    //进行数据处理,休眠 0-1000毫秒模拟耗时
                    Thread.sleep(1000);
                    System.out.println("当前消费者线程"+Thread.currentThread().getName() +",消费成功,消费id为"+data.getId());
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

long-king

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值