java - 使用 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(和一般编程)非常陌生。太感谢了!
解决方案
推荐阅读
- django - 为什么会出现这个错误,docker操作错误(django项目)?
- javascript - 如何在单击按钮时从全日历中删除事件?
- reactjs - React 组件安装生命周期调用两次 react 16.13.1
- r - 无法解决“警告:因素 `officialTitle` 包含隐式 NA,考虑使用 `forcats::fct_explicit_na`”
- javascript - 如何使用 addeventlistener 附加子级
- ssis - 从平面文件读取时,SSIS 正在四舍五入十进制值
- python - Flask 参数不能带特殊字符(>=、==、< 等...)
- java - 如何在java中通过json传递二进制文件?
- reactjs - 我想修改我收到的道具
- xml - XSLT - 无法提取给定节点的子节点