LinkedBlockingQueue 阻塞队列实现生产/消费模型

位置:首页>文章>详情   分类: 教程分享 > Java教程   阅读(1401)   2023-03-28 11:29:14
LinkedBlockingQueue 阻塞队列实现生产/消费模型
package com.example.demospringbootqueueasynctask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;

/***
 * 通过阻塞队列实现 生产/消费模型的异步任务。
 */
@Service
public class QueueService {
    private static Logger logger = LoggerFactory.getLogger(QueueService.class);
    /**
     * 使用阻塞队列实现 生产消费模型
     * 下面例子中的数据类型暂定为String
     */
    public static LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>();

    /***
     * 线程池,多线程任务处理
     */
    private static ExecutorService threadPool = Executors.newFixedThreadPool(3);


    //启执行
    @PostConstruct
    private void consumer() {
        for (int i = 0; i < 3; i++) {
            threadPool.execute(() -> {
                        while (true) {
                            String message = null;
                            try {
                                Thread.sleep(50);//休息
                                message = queue.take();
                                //模拟消费队列---->做一个输出操作
                                System.out.println("接收到消息:[" + Thread.currentThread().getName() + "]" + message);
                            } catch (Exception e) {
                                logger.error("企业知产同步队列发生了异常:", e);
                                //异常情况可以根据业务考虑是否需要重新放入队列
                                /*if (!StringUtils.isEmpty(message)){
                                    queue.add(message);
                                }*/
                            }
                        }
                    }
            );
        }
    }

    /**
     * 生产者
     */
    public void producer(String message) {
        if (StringUtils.isEmpty(message)) {
            throw new RuntimeException("内容不能为空");
        }
        queue.add(message);
    }

}
 
地址:https://www.leftso.com/article/510.html

相关阅读

LinkedBlockingQueue 阻塞队列实现生产/消费模型package com.example.demospringbootqueueasynctask; import org.sl...
线程池创建 /** * 队列用线程 * @return */ @Bean(name = "queuePool") public Thread...
java Queue队列实现生产消费模式,什么是Java编程中的Queue(队列),手动实现生产者消费者模式