首页 > 解决方案 > 使用 ScheduledExecutorService 时出现这种奇怪输出的原因是什么?

问题描述

我正在创建一个哈希图,当交易实时发生时,它汇总了一组股票的交易量。我想每分钟“重新设置”成交量哈希图,并在接下来的一分钟内对下一组成交量求和,在整个交易日重复这个过程。

到目前为止我有这个:

Double vol; 
String mS;
Map<String, Double> volMap = new HashMap<String, Double>();
Map<String, Double> volMapAdd = new HashMap<String, Double>();

     for (Trade trade : events) {     //this iterates through an Array of stock symbols
         vol = trade.getSizeAsDouble();  //this method calls the volume of the iterated symbol
         mS = trade.getEventSymbol();  //this method calls the stock symbol for the associated trade
         if (mS != null)               //checks if null
            volMap.put(mS, vol);          //then adds the volume and symbol to a Hashmap
         if (mS != null)   
            volMapAdd.putIfAbsent(mS,vol);  //this creates a baseline for the summation Hashmap
         if (vol !=null & volMapAdd.get(mS) !=null)
            volMapAdd.computeIfPresent(mS,(k,v) -> v + vol); //this creates the summation Hashmap

         System.out.println(volMapAdd.entrySet());
         executorService.schedule(new Runnable( ) {
            @Override
            public void run() {
                System.out.println("initiating");
                volMapAdd.putAll(volMap);     //re-sets the summation Hashmap to volMap current state
                System.out.println(volMapAdd.entrySet() + " after reset");
            }
        }, 30, TimeUnit.SECONDS);
    }
    while (!Thread.interrupted())            //creates an endless loop
        Thread.sleep(1000);

程序运行良好,在最初的 30 秒延迟内将所选品种的交易量相加,然后运行 ​​run() 方法并“重新设置”总和 Hashmap volMapAdd。但在那之后,我得到多个“初始化”实例被打印到控制台,表明 run() 方法被多次调用。我不知道不同线程是否发生了一些奇怪的事情,或者每个循环的初始值是否导致 run() 方法被多次调用。任何帮助解决这个问题将不胜感激。另外,我对java(和一般编程)非常陌生。太感谢了!

标签: javaforeachinfinite-loopscheduledexecutorservice

解决方案


推荐阅读