Java 如何使用executor服务从多个文件执行添加并给出最终输出

Java 如何使用executor服务从多个文件执行添加并给出最终输出,java,executorservice,Java,Executorservice,下面是我尝试过的一段代码。每个文件都有一个整数,我想添加所有整数并显示输出 @Override public void run() { BlockingQueue<Integer> d; try { d = readFile(file); //System.out.println("adding the integers ..."+d.take()); i = (int) d.take(); System

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

@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;
}
@覆盖
公开募捐{
阻塞队列d;
试一试{
d=读取文件(文件);
//System.out.println(“添加整数…”+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);
}捕获(IOException | InterruptedException e){
e、 printStackTrace();
}
//ProcessedData p=d.process();
//writeFile(file.getAbsolutePath(),“C:/test”);
}
private BlockingQueue readFile(文件file2)引发IOException、InterruptedException{
FileReader fr=新的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(“读取和写入阻塞队列…”);
blockingQueue.put(内容);
返回阻塞队列;
}

以下是问题的解决方案-

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

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

我已经分段并创建了一个singleton类,它在请求时为每个线程返回相同的原子整数对象

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

导入java.util.concurrent.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;
}

}

从第一眼看,您似乎混淆了
BlockingQueue
的用法,因为
sum
变量永远不会正确返回,请检查此项和此项,这可能与您的用例更相关,我不明白为什么我不能在executorserivce和add中使用blockingqueue?如果有人能帮忙,我将不胜感激!!不,我不是说你不能,我是说你有点过于复杂的过程。另外,您正在使用2个
FileReader
实例,而没有实际使用。在您的示例中,
sum
引用看起来像一个私有线程变量,这意味着没有人可以访问它!?!那你打算把它打印出来吗?或者实际被阻止的线程应该对队列中的所有值进行计数?