java阻塞队列生产消费_用阻塞队列实现生产者消费者模式(单线程消费)

生产者消费者模式不在23种常用设计模式里面,但在实际工作中也经常会用到。特别是在将数据的生产者和消费者解耦,或者用多线程优化性能时派上用场。

一、代码目录结构

2d92a688e017172abe5536a35397d02b.png

目录说明:

config:Swagger配置,方便通过swagger调用接口测试.

constant: 枚举常量定义。

model:模型定义。

rest: restful接口定义。

service: 实现业务逻辑。

二、核心代码说明

1. EnumTaskEndType

定义了几种常用的任务结束方式:

package com.elon.constant; /**

* 任务结束方式

*

* @author elon

* @version 1.0

*/ public enum EnumTaskEndType { /**

* 无效类型

*/ NA, /**

* 任务完成结束

*/ COMPLETE, /**

* 任务被终止结束

*/ TERMINATE; }

Task

定义任务模型,这个是生产者消费者核心模型,包含哪些数据根据具体的业务要求来定义.

package com.elon.model; import com.alibaba.fastjson.JSONObject; import com.elon.constant.EnumTaskEndType; /**

* 任务模型. 任务模型中存储生产者和消费者沟通信息. 具体存储什么信息根据实际的业务来。

*

* @author elon

* @version 1.0

*/ public class Task { /**

* 任务名称

*/ private String taskName = ""; /**

* 任务结束方式(此字段用于标识任务是否为毒丸任务)

*/ private EnumTaskEndType taskEndType = EnumTaskEndType.NA; public String getTaskName() { return taskName; } public void setTaskName(String taskName) { this.taskName = taskName; } public EnumTaskEndType getTaskEndType() { return taskEndType; } public void setTaskEndType(EnumTaskEndType taskEndType) { this.taskEndType = taskEndType; } public String toString() { return JSONObject.toJSONString(this); } }

2. ProduceConsumerController

生产者消费者接口层,用于定义rest接口。方便自测试.

package com.elon.rest; import com.elon.service.ProConsService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/v1/produce-consumer") @Api(tags = "生产者消费者服务") public class ProduceConsumerController { @PostMapping("/start-task/{taskAmount}") @ApiOperation(value = "启动服务任务") public String startTask(@PathVariable("taskAmount") int taskAmount) { ProConsService proConsService = new ProConsService(); proConsService.startTask(taskAmount); return ""; } }

3. Consumer

消费者。负责任务处理。消费者收到毒丸任务后将毒丸放回队列头( 目的是为了让其它消费者也能尽快收到毒丸结束整个任务),然后退出线程。

package com.elon.service; import com.elon.constant.EnumTaskEndType; import com.elon.model.Task; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; /**

* 消费者类. 负责从队列中取出任务消费.

*

* @author elon

* @version 1.0

*/ public class Consumer implements Runnable { private static final Logger LOGGER = LogManager.getLogger(Consumer.class); /**

* 阻塞队列

*/ private LinkedBlockingDeque blockingDeque = null; public Consumer(LinkedBlockingDeque blockingDeque) { this.blockingDeque = blockingDeque; } @Override public void run() { while (true) { try { Task task = blockingDeque.take(); // 收到毒丸任务将毒丸放回队列头,结束当前线程. if (task.getTaskEndType() != EnumTaskEndType.NA) { LOGGER.info("收到毒丸任务.{}", task); blockingDeque.offerFirst(task, 2, TimeUnit.MILLISECONDS); break; } // 消费任务. 这里可以写实际的业务逻辑. LOGGER.info("消费任务:{}", task); } catch (InterruptedException e) { e.printStackTrace(); } } LOGGER.info("消费者结束消费."); } }

4. Producer

生产者,负责将生产任务放入队列。生产者在生产完所有正常的数据处理任务后,在队列尾放入一个毒丸任务,使消费者线程在处理完所有任务后能退出线程,避免无限等待。

package com.elon.service; import com.elon.constant.EnumTaskEndType; import com.elon.model.Task; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; /**

* 生产者类. 负责创建任务放到阻塞队列.

*

* @author elon

* @version 1.0

*/ public class Producer implements Runnable { private static final Logger LOGGER = LogManager.getLogger(Producer.class); private LinkedBlockingDeque blockingDeque = null; private final int taskAmount; public Producer(LinkedBlockingDeque blockingDeque, int taskAmount) { this.blockingDeque = blockingDeque; this.taskAmount = taskAmount; } @Override public void run() { for (int i = 1; i <= taskAmount; ++i) { try { Task task = new Task(); task.setTaskName("任务:" + i); blockingDeque.offer(task, 2, TimeUnit.MILLISECONDS); LOGGER.info("生产任务:{}", task); } catch (InterruptedException e) { LOGGER.error("创建任务异常.", e); } } // 放入毒丸任务已结束消费者线程 try { Task task = new Task(); task.setTaskName("任务处理结束毒丸"); task.setTaskEndType(EnumTaskEndType.COMPLETE); blockingDeque.offer(task, 2, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); } } }

5. ProConsService

负责生产者和消费者线程初始化.

package com.elon.service; import com.elon.model.Task; import java.util.concurrent.LinkedBlockingDeque; /**

* 生产者消费者服务。启动生产者消费者线程.

*

* @author elon

* @version 1.0

*/ public class ProConsService { private LinkedBlockingDeque blockingDeque = new LinkedBlockingDeque<>(); /**

* 开始任务.

*

* @param taskAmount 生产的任务数量

* @author elon

*/ public void startTask(int taskAmount) { Producer producer = new Producer(blockingDeque, taskAmount); new Thread(producer).start(); Consumer consumer = new Consumer(blockingDeque); new Thread(consumer).start(); } }

6. ProducerConsumerApplication

SpringBoot应用启动类

package com.elon; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ProducerConsumerApplication { public static void main(String[] args) { SpringApplication.run(ProducerConsumerApplication.class); System.out.println("Startup ProducerConsumerApplication success."); } }

三、通过swagger接口测试

dd4ba0e15b86ab7d1953195f8d7ed0f2.png

从打印的信息来看。消费者线程在收到标识所有任务已完成毒丸后就结束消费了。这是已知生产者需要生产多少任务的情况,如果生产任务数量不确定,则需要根据外部输入的数据实时生成任务。

本文地址:https://blog.csdn.net/ylforever/article/details/108031627

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值