如何使用执行程序服务从多个文件执行加法并提供最终输出

问题描述 投票:0回答:1

下面是我尝试过的一段代码。每个文件都有一个整数,我想将所有整数相加并显示输出

@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;
}
java executorservice
1个回答
0
投票

这是问题的解决方案-

当我使用原子整数将队列中的所有整数相加时,每个线程都有一个原子变量的不同副本。

因此,每次使用addAndGet方法时,都会使用阻塞队列中的值对其进行更新。

我已隔离并创建了一个单例类,当需要时,该类为每个线程返回相同的原子整数对象。

下面是代码段,这解决了我的问题-

导入java.util.concurrent.atomic.AtomicInteger;

公共类AtomicState {

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;
}

}

© www.soinside.com 2019 - 2024. All rights reserved.