首页 > 其他分享 >ArrayBlockingQueue使用

ArrayBlockingQueue使用

时间:2024-02-01 19:55:22浏览次数:19  
标签:Thread int void 使用 producerThreadList new ArrayBlockingQueue

package org.example;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 用数组实现的阻塞队列
 */
public class ArrayBlockingQueueDemo {
    ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
    volatile boolean isStop = false;

    public static void main(String[] args) {
        ArrayBlockingQueueDemo demo = new ArrayBlockingQueueDemo();
        demo.test();
    }

    private void test() {
        List<Thread> producerThreadList = new ArrayList<>();
        List<Thread> consumerThreadList = new ArrayList<>();
        for (int j = 0; j < 3; j++) {
            producerThreadList.add((new Thread(this::producer, "包⼦⽣产商_" + j)));
        }
        for (int j = 0; j < 2; j++) {
            consumerThreadList.add((new Thread(this::consumer, "消息者_" + j)));
        }
        producerThreadList.forEach(Thread::start);
        consumerThreadList.forEach(Thread::start);

        producerThreadList.forEach(this::threadJoin);
        isStop = true;
    }

    private void producer() {
        try {
            for (int j = 0; j < 4; j++) {

                System.out.println(Thread.currentThread().getName() + ", ⽣产包⼦_" + j);
                queue.put("包⼦_" + j);
                Thread.sleep(200);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void consumer() {
        try {
            while (!isStop) {

                System.err.println(Thread.currentThread().getName() + ", 买到包⼦:" + queue.take());
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void threadJoin(Thread thread) {
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

改造后:

package org.example;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;

/**
 * 用数组实现的阻塞队列
 *
 * 如果消费者在前,生产者在后,就会出现消费者线程已经退出,又生产了几个包子,然后没有线程消费
 * 主要是讲解阻塞队列的使用情况,其实你可以发现,在案例中,生产和消费基本上是持平的,没有出现疯狂生产而消费跟不上的情况。
 * 具体说生产了几个,消费了几个就无所谓了
 * 可以理解为阻塞队列的加入,协调了生产和消费,相当于做了限流处理
 */
public class ArrayBlockingQueueDemo1 {
    ArrayBlockingQueue queue = new ArrayBlockingQueue(3);
    volatile boolean isStop = false;

    public static void main(String[] args) throws InterruptedException {
        ArrayBlockingQueueDemo1 demo = new ArrayBlockingQueueDemo1();
        demo.test();
    }

    private void test() throws InterruptedException {
        List<Thread> producerThreadList = new ArrayList<>();
        List<Thread> consumerThreadList = new ArrayList<>();
        for (int j = 0; j < 3; j++) {
            int finalJ = j;
            producerThreadList.add((new Thread(() -> {
                producer(finalJ); // finalJ
            }, "包⼦⽣产商_" + j)));
        }
        for (int j = 0; j < 2; j++) {
            consumerThreadList.add((new Thread(this::consumer, "消息者_" + j)));
        }
        producerThreadList.forEach(Thread::start);
        consumerThreadList.forEach(Thread::start);

        Thread.sleep(50000);

        producerThreadList.forEach(this::threadJoin);
        isStop = true;
    }

    private void producer(int flag) {
        try {
            for (int j = 0; j < 4; j++) {

                System.out.println(Thread.currentThread().getName() + ", ⽣产包⼦_" + j);
                queue.put("包⼦_" + flag + "=" + j);
                Thread.sleep(200);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void consumer() {
        try {
            while (!isStop) {

                System.err.println(Thread.currentThread().getName() + ", 买到包⼦:" + queue.take());
                Thread.sleep(1000);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void threadJoin(Thread thread) {
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

两者运行结果对比:

标签:Thread,int,void,使用,producerThreadList,new,ArrayBlockingQueue
From: https://www.cnblogs.com/dongyaotou/p/18002001

相关文章

  • 局域网内已使用IP查询
    1、使用windows自带cmd命令查询本机IP-信息,见下图; 2、输入命令:for/L%iIN(1,1,254)DOping-w2-n110.70.65.%iping-w2-n110.70.65.1 3、返回数据通过丢包信息判断对应IP是否被使用;10.70.65.3(100%丢失)表示对应IP未使用;10.70.65.4(0%丢失)......
  • 快乐学Python,如何正确使用pandas处理时间类型的数据?
    在日常的数据分析工作中,常常会有根据日期来对数据进行分析。比如我们需要通过用户的下单时间来分析用户在不同时间段对商品的喜好;如通过访问日志的访问时间来分析系统的访问周期和负载,为不同时间段的资源调配提供依据;如通过用户刷短视频的时间来分析用户的行为特征和工作时间和工种......
  • OGNL 基础使用和入门
    一、什么是OGNLOGNL是ObjectGraphNavigationLanguage的缩写,中文意思是对象导航图语言。它是一种开源的表达式语言(ExpressionLanguage),被集成在Struts2等框架中,主要用于对数据进行访问。它拥有类型转换、访问对象方法、操作集合对象等功能,并可以通过简单的语法存取对象的任意属......
  • 使用spring-jpa和 hibernate实现逻辑删除
    一、使用spring-jpa和hibernate的@SQLDelete和@Where注解实现逻辑删除逻辑删除定义逻辑删除是指在删除数据库的某条记录时,并不是真正的将该条记录删除,而是通过某个字段来标识其状态为“删除”,在接下来的查询等操作时,根据此字段来过滤调被删除的记录。使用Hibernate进行逻辑删除......
  • Blazor里,如何在 razor 页面使用 BackgroundService 实例
    Blazor使用BackgroundService需要注册builder.Services.AddHostedService<PageStateService>();razor页面要使用 PageStateService的实例,需要 PageStateService有接口,我们给PageStateService写一个接口 IPageStateService然后在页面直接注入实例@injectIPageSt......
  • Kubernetes 为用户使用 Dashboard 创建 RBAC 权限
    文章目录目录文章目录一、创建Namespace二、创建ServiceAccount三、创建Namespace的RBAC权限1、方式一:使用系统提供角色分配Namespace权限2、方式二:使用自定义角色分配Namespace权限四、解决登录Dashboard不能选择Namespace问题系统环境:kubernetes版本:1.16.3......
  • 「效果图渲染」揭秘渲染效果图灯光使用技巧
    在三维渲染中,光线的部署如同绘画作品中的色彩调配,至关重要,一个精心设计的照明方案能赋予效果图以生命,凸显质感,营造深度,并传达特定氛围。在灯光设置过程中,先思考光源的类型与位置,从而确保光线恰如其分地照亮关键的视觉元素,模拟现实世界的光照原理,也激发出艺术的想象空间。渲染效......
  • 谭浩强 第5版 第8章 第2题(使用strcmp)
    题目:输入3个字符串,要求按由小到大的顺序输出。代码实现:#define_CRT_SECURE_NO_WARNINGS1#include<stdio.h>intmain(){ chararr[3][20]={0}; char*p[3]={0}; inti=0; intj=0; char*tem=NULL; //输入 for(i=0;i<3;i++) { scanf("%s",......
  • Spring Data审计功能@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy
    在SpringJPA中,在实体bean的属性上加注解@CreatedDate、@CreatedBy、@LastModifiedDate、@LastModifiedBy,可以再实体插入数据库时进行设置值,这样以来,在对普通实体类的添加、修改操作时,就不用关心创建时间、更新时间这些信息了。本文以SpringBoot为例1、引入依赖<dependency><......
  • 使用js获取系统分辨率、系统缩放倍数和浏览器缩放倍数
    做屏幕适配让人头大,用rem适配需要获取到系统缩放倍数和浏览器缩放倍数来计算根节点字体大小,网上找来找去都没看见一个满意的方案,自己折腾一个算是一个比较完美的方案吧,亲测谷歌浏览器120版本有效//获取缩放倍数(1*系统缩放倍数*浏览器缩放倍数)functiongetZoom(){letzoom=......