热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

多线程模式(5):生产者消费者模式

为什么80%的码农都做不了架构师?定义共享数据封装packagecom.xqi.p_c;***请求数据封装(以不变模式定义)**au

为什么80%的码农都做不了架构师?>>>   hot3.png

  1. 定义共享数据封装

package com.xqi.p_c;/*** 请求数据封装(以不变模式定义)* * @author mike 
*         2015年7月24日*/
public final class PCData {private final int intData;public PCData(int d) {intData = d;}public PCData(String d) {intData = Integer.valueOf(d);}public int getData(){return this.intData;}@Overridepublic String toString() {return "data:" + intData;}}

 2. 定义生产者

package com.xqi.p_c;import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;/*** 定义生产者* * @author mike 
*         2015年7月24日*/
public class Produer implements Runnable {/* 用volatile来修饰的变量,表示随时都可能被其他的线程来改变,并使其他的线程直接访问此变量,而不保存其他的备份! */private volatile boolean isRunning = true;/* 定义内存缓冲区,来存放生产者提交的请求与数据, PCData就是数据的封装 */private BlockingQueue queue;/* 总数,原子操作 ,AtomicInteger提供线程安全的加减操作接口 */private static AtomicInteger count = new AtomicInteger();/* 休眠时间 */private static final int SLEEPTIME = 1000;/*** 构造方法,注入缓冲队列* * @param queue*/public Produer(BlockingQueue queue) {this.queue = queue;}public void run() {PCData data = null;Random r = new Random();System.out.println("start produer id = " + Thread.currentThread().getId());try {while (isRunning) {Thread.sleep(r.nextInt(SLEEPTIME)); // 使用随机产生时间差(消费者中一样)data = new PCData(count.incrementAndGet());// incrementAndGet表示+1System.out.println(data + " is put into queue!");if (!queue.offer(data, 2, TimeUnit.SECONDS)) {// 设定等待的时间为2秒,如果在指定的时间内,还不能往队列中加入,则返回失败。System.err.println("failed to put data : " + data);}}} catch (InterruptedException e) {// 如果发生了异常就中断这个线程e.printStackTrace();Thread.currentThread().interrupt();}}//public void stop() {isRunning = false;}
}

 3. 定义消费者

package com.xqi.p_c;import java.text.MessageFormat;
import java.util.Random;
import java.util.concurrent.BlockingQueue;/*** 消费者* * @author mike 
*         2015年7月24日*/
public class Consumer implements Runnable {private BlockingQueue queue;private static final int SLEEPTIME = 1000;public Consumer(BlockingQueue queue) {this.queue = queue;}public void run() {System.out.println("start consumer id = " + Thread.currentThread().getId());Random r = new Random();try {while (true) {PCData data = queue.take();// 取走BlockingQueue里排在首位的对象,若BlockingQueue为空,阻断进入等待状态直到Blocking有新的对象被加入为止if (null != data) {int re = data.getData() * data.getData();System.out.println(MessageFormat.format("{0}*{1}={2}", data.getData(), data.getData(), re));Thread.sleep(r.nextInt(SLEEPTIME));}}} catch (InterruptedException e) {e.printStackTrace();Thread.currentThread().interrupt();}}}

 4. 测试主类

package com.xqi.p_c;import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;/*** 测试主类* * @author mike 
*         2015年7月24日*/
public class PCTest {public static void main(String[] args) throws InterruptedException {BlockingQueue queue = new LinkedBlockingQueue(10);// 创建生产者Produer p1 = new Produer(queue);Produer p2 = new Produer(queue);Produer p3 = new Produer(queue);// 创建消费者Consumer c1 = new Consumer(queue);Consumer c2 = new Consumer(queue);Consumer c3 = new Consumer(queue);// 创建线程池,newCachedThreadPool 定义了短期可重用的线程池ExecutorService service = Executors.newCachedThreadPool();// 运行生产者和消费者service.execute(p1);service.execute(p2);service.execute(p3);service.execute(c1);service.execute(c2);service.execute(c3);Thread.sleep(10 * 1000);// 终止线程中的whilep1.stop();p2.stop();p3.stop();Thread.sleep(3000);// shutdown() This method does not wait for previously submitted tasks to complete execution.// shutdown() 这个方法不会等待任务执行完成。(有说:不再接受新的任务,如果有等待的任务,就执行完成)service.shutdown();// Attempts to stop all actively executing tasks, halts the// processing of waiting tasks, and returns a list of the tasks// that were awaiting execution. These tasks are drained (removed)// from the task queue upon return from this method.// 立即变为shutdown状态,如果有正在执行的任务,尝试停止,并返回未完成的任务列表,然后移除// List taskList = service.shutdownNow();System.out.println("程序结束!");}}


Ps:感觉shutdown了以后,线程还是没有终止,也进行不了操作??????不知道为什么!



转:https://my.oschina.net/rwrwd7/blog/483317



推荐阅读
  • 本文介绍了Java并发库中的阻塞队列(BlockingQueue)及其典型应用场景。通过具体实例,展示了如何利用LinkedBlockingQueue实现线程间高效、安全的数据传递,并结合线程池和原子类优化性能。 ... [详细]
  • Explore how Matterverse is redefining the metaverse experience, creating immersive and meaningful virtual environments that foster genuine connections and economic opportunities. ... [详细]
  • Explore a common issue encountered when implementing an OAuth 1.0a API, specifically the inability to encode null objects and how to resolve it. ... [详细]
  • Java 中的 BigDecimal pow()方法,示例 ... [详细]
  • 本文深入探讨了 Java 中的 Serializable 接口,解释了其实现机制、用途及注意事项,帮助开发者更好地理解和使用序列化功能。 ... [详细]
  • 本文详细介绍了Akka中的BackoffSupervisor机制,探讨其在处理持久化失败和Actor重启时的应用。通过具体示例,展示了如何配置和使用BackoffSupervisor以实现更细粒度的异常处理。 ... [详细]
  • Android 渐变圆环加载控件实现
    本文介绍了如何在 Android 中创建一个自定义的渐变圆环加载控件,该控件已在多个知名应用中使用。我们将详细探讨其工作原理和实现方法。 ... [详细]
  • 本文探讨了如何在给定整数N的情况下,找到两个不同的整数a和b,使得它们的和最大,并且满足特定的数学条件。 ... [详细]
  • 从 .NET 转 Java 的自学之路:IO 流基础篇
    本文详细介绍了 Java 中的 IO 流,包括字节流和字符流的基本概念及其操作方式。探讨了如何处理不同类型的文件数据,并结合编码机制确保字符数据的正确读写。同时,文中还涵盖了装饰设计模式的应用,以及多种常见的 IO 操作实例。 ... [详细]
  • 本文介绍了如何通过 Maven 依赖引入 SQLiteJDBC 和 HikariCP 包,从而在 Java 应用中高效地连接和操作 SQLite 数据库。文章提供了详细的代码示例,并解释了每个步骤的实现细节。 ... [详细]
  • PyCharm下载与安装指南
    本文详细介绍如何从官方渠道下载并安装PyCharm集成开发环境(IDE),涵盖Windows、macOS和Linux系统,同时提供详细的安装步骤及配置建议。 ... [详细]
  • 本文介绍如何使用Objective-C结合dispatch库进行并发编程,以提高素数计数任务的效率。通过对比纯C代码与引入并发机制后的代码,展示dispatch库的强大功能。 ... [详细]
  • 本文介绍了如何使用 Spring Boot DevTools 实现应用程序在开发过程中自动重启。这一特性显著提高了开发效率,特别是在集成开发环境(IDE)中工作时,能够提供快速的反馈循环。默认情况下,DevTools 会监控类路径上的文件变化,并根据需要触发应用重启。 ... [详细]
  • 1.如何在运行状态查看源代码?查看函数的源代码,我们通常会使用IDE来完成。比如在PyCharm中,你可以Ctrl+鼠标点击进入函数的源代码。那如果没有IDE呢?当我们想使用一个函 ... [详细]
  • 深入探讨CPU虚拟化与KVM内存管理
    本文详细介绍了现代服务器架构中的CPU虚拟化技术,包括SMP、NUMA和MPP三种多处理器结构,并深入探讨了KVM的内存虚拟化机制。通过对比不同架构的特点和应用场景,帮助读者理解如何选择最适合的架构以优化性能。 ... [详细]
author-avatar
Chinaexpoinfo
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有