java - 如何使用执行器服务从多个文件中执行添加并给出最终输出
问题描述
下面是我尝试过的一段代码。每个文件都有一个整数,我想添加所有整数并显示输出
@Override
public void run() {
BlockingQueue<Integer> d;
try {
d = readFile(file);
//System.out.println("adding the integers ..."+d.take());
i = (int) d.take();
System.out.println("i = "+i);
sum = sum + i;
//System.out.println("ai = "+ai.incrementAndGet());
System.out.println("sum = "+sum );
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
// ProcessedData p = d.process();
// writeFile(file.getAbsolutePath(), "C:/test");
}
private BlockingQueue<Integer> readFile(File file2) throws IOException, InterruptedException {
FileReader fr = new FileReader(file2);
BufferedReader in = new BufferedReader(new java.io.FileReader(file2));
int content = Integer.parseInt(in.readLine());
System.out.println("content = "+content);
System.out.println("reading and writing to blocking queue...");
blockingQueue.put(content);
return blockingQueue;
}
解决方案
这是问题的解决方案 -
当我使用原子整数从队列中添加所有整数时,每个线程都有不同的原子变量副本。
因此,每次使用 addAndGet 方法时,都会使用阻塞队列中的值进行更新。
我已经隔离并创建了一个单例类,它在请求时为每个线程返回相同的原子整数对象。
下面是代码片段,这解决了我的问题 -
导入 java.util.concurrent.atomic.AtomicInteger;
公共类原子状态{
private static final AtomicState as = new AtomicState();
public AtomicInteger ai = new AtomicInteger();
private AtomicState() {
}
public AtomicInteger getAtomicIntegerObj() {
return ai;
}
public static AtomicState getAtomicState() {
return as;
}
}
推荐阅读
- python - 如何在不丢失行的情况下合并 Time Series Panda 数据框?
- php - 创建将匹配字符串中的要求的正则表达式
- java - 在 Java 应用程序中,有没有办法格式化/缩进 XSLT 文档?
- highcharts - 最大不能有 highcharts x 轴标签
- javascript - Aurelia bindingEngine.propertyObserver - 检测何时因对象更改而更改属性
- apache-camel - 如何在 Apache Camel 中安排 JMS 消费?
- laravel - Laravel JOIN 查询有 2 个条件,其中一个为 NULL
- java - 将非 Web 客户端的用户名和密码传递给 RestController Service 并在 Service 中检索
- ios - 是否必须使用 Assets.xcassets?
- circleci - Circleci 在工作流作业中传递 docker 图像