首页 > 解决方案 > 如何使用执行器服务从多个文件中执行添加并给出最终输出

问题描述

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

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

标签: javaexecutorservice

解决方案


这是问题的解决方案 -

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

因此,每次使用 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;
}

}


推荐阅读