首页 > 其他分享 >多线程map添加

多线程map添加

时间:2024-05-08 17:13:51浏览次数:12  
标签:map Map 添加 new import 多线程 public unit

import com.alibaba.fastjson.JSONObject;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;

/**
 * map中添加多个执行漫的值,使用多线程的方式执行
 */
public class AsynInitMapUtil {

    private ReentrantLock lock;
    private Map resultMap;
    private Integer timeOut; //执行超时时间
    private TimeUnit unit; //执行超时时间单位
    private ExecutorService executorService;
    private List<Supplier<Map>> supplierList;

    public AsynInitMapUtil(int timeOut, TimeUnit unit) {
        this.resultMap = new HashMap();
        this.timeOut = timeOut;
        this.unit = unit;
        this.supplierList = new ArrayList<>();
        this.lock = new ReentrantLock();
        this.executorService = Executors.newCachedThreadPool();
    }

    public AsynInitMapUtil(Map map, int timeOut, TimeUnit unit) {
        this.supplierList = new ArrayList<>();
        this.lock = new ReentrantLock();
        this.resultMap = map;
        this.timeOut = timeOut;
        this.unit = unit;
        this.executorService = Executors.newCachedThreadPool();
    }


    public static void main(String[] args) {
        Map myMap = new HashMap();
        myMap.put("test", true);

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println(simpleDateFormat.format(new Date()));
        new AsynInitMapUtil(myMap,5, TimeUnit.SECONDS)
                .addTask(() -> {
                    Map map = new HashMap();
                    map.put("a1", 111);
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    return map;
                }).addTask(() -> {
            Map map = new HashMap();
            map.put("a2", 222);
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return map;
        }).addTask(() -> {
            Map map = new HashMap();
            map.put("a3", 333);
            return map;
        }).execute();

        System.out.println(JSONObject.toJSONString(myMap));
        System.out.println(simpleDateFormat.format(new Date()));
    }

    /**
     * 执行多任务
     *
     * @return
     */
    public AsynInitMapUtil execute() {
        try {
            CountDownLatch cd = new CountDownLatch(supplierList.size());
            for (Supplier<Map> supplier : supplierList) {
                threadRun(() -> {
                    try {
                        initMap(supplier.get());
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        cd.countDown();
                    }
                });
            }
            cd.await(this.timeOut, unit);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if (this.executorService != null) {
                    this.executorService.shutdown();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return this;
    }

    public AsynInitMapUtil addTask(Supplier<Map> supplier) {
        supplierList.add(supplier);
        return this;
    }

    public void initMap(Map map) {
        lock.lock();
        try {
            resultMap.putAll(map);
        } finally {
            lock.unlock();
        }
    }

    /**
     * 线程异步执行
     *
     * @param
     */
    public void threadRun(VoidTask voidTask) {
        executorService.execute(() -> {
            voidTask.execute();
        });
    }

    public Map getResultMap() {
        return resultMap;
    }

    public void setResultMap(Map resultMap) {
        this.resultMap = resultMap;
    }


    @FunctionalInterface
    private interface VoidTask {
        void execute();
    }
}

 

标签:map,Map,添加,new,import,多线程,public,unit
From: https://www.cnblogs.com/zhiyong-666/p/18180254

相关文章

  • 多线程填充实体类
    importcom.alibaba.fastjson.JSONObject;importjava.text.SimpleDateFormat;importjava.util.*;importjava.util.concurrent.CountDownLatch;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.Tim......
  • 【HarmonyOS Next】多线程网络请求简单封装
    importhttpfrom'@ohos.net.http';import{taskpool}from'@kit.ArkTS';exportclassRequest{staticasyncget(url:string,header?:Object,expectDataType:http.HttpDataType=http.HttpDataType.OBJECT):Promise<Object>{......
  • GreatSQL的sp中添加新的sp_instr引入的bug解析
    GreatSQL的sp中添加新的sp_instr引入的bug解析一、问题发现在一次开发中用到的sp需要添加新的sp_instr以满足需求,但是添加了数个sp_instr以后发现执行新的sp会发生core。注:本次使用的GreatSQL8.0.32-251、sp_head.cc的init_sp_psi_keys()代码里面添加10个新的sp_instr:void......
  • 原始翎风CLIENT8位 (14) mapunit的学习
    8.MaxInt格式:constMaxInt=High(integer);说明:MaxInt常量代表Integer类型的最大可能值.MaxInt的真正的值会随着Delphi的版本不同而改变,目前它的值是21474836472g?地图好像是分块?40*40个地图坐标分为一个广场块一次读取是当前块的-1X/Y+2合计4*4块合计160*160个......
  • c# 多线程的几种方式 【转载】
    1.什么是线程?进程作为操作系统执行程序的基本单位,拥有应用程序的资源,进程包含线程,进程的资源被线程共享,线程不拥有资源。 2.前台线程和后台线程的区别?程序关闭时,后台线程直接关闭,但前台线程会执行完后关闭。通过Thread类新建线程默认为前台线程。其他方式创建的都是后台线程......
  • allure功能使用-测试时添加文件attach
    allure.attach("getenv","附加文本",attachment_type=allure.attachment_type.TEXT)allure.attach("<body>测试body</body>","html代码",attachment_type=allure.attachment_type.HTML)allure.attach.file("./test.p......
  • allure功能使用-添加链接link&testcase&issue
    1.执行指定测试用例时,在测试方法前添加注解@allure.link跳转到执行地址: 在HTML报告可看到跳转信息: 2.执行指定测试用例时,需要知道测试案例所在代码仓库地址时,在其方法前添加注解@allure.testcase跳转仓库地址(用于代码走读):  3.执行指定测试用例时,需要将该用例关联到缺......
  • Java 集合框架的collection接口和map接口
    集合框架中整体的架构分为2类:Collection接口和Map接口Collection接口:用于存储单个对象的典型的实现类:List--->ArryListLinkedListSet--->HashSetThreeSetMap接口:用于存储K-V键值对双对象的典型的实现类:HashMap一、ArrayList1.1、简介数据存储:底层采用的是数组,但是采......
  • easyui给iframe添加样式文件
    需求:有一个用easyui做的后台管理项目,已经上线运行好多年,在不影响功能运行的前提下美化页面。需要给所有的iframe添加样式文件;代码如下://iframe的id为mainIframe<iframeid="mainIframe"name="mainIframe"onload="iframeClick(this)"frameBorder="0"scrolling="auto"......
  • jmap使用报错Doesn't appear to be a HotSpot VM (could not find symbol "gHotSpotVM
    报错场景问题原因服务器上装了jdk,按理来说jmap是自带了的,可以直接使用,根据情况来看是装了jmap但是无法正常使用,推测是版本的问题导致解决方式指定jdk自带的jmap工具1.查看当前java的环境变量echo$JAVA_HOME2.配置jdk自带工具的环境变量exportPATH=$JAVA_HOME/bin:$P......