如何使用执行程序服务从多个文件执行添加并给出最终输出
How to perform addition from multiple files using executor service and gives final output
下面是我试过的一段代码。每个文件都有一个整数,我想将所有整数相加并显示输出
@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 方法时,都会使用阻塞队列中的值进行更新。
我已经隔离并创建了一个单例 class,其中 returns 我在请求时为每个线程使用相同的原子整数对象。
下面是代码片段,这解决了我的问题 -
导入java.util.concurrent.atomic.AtomicInteger;
public class 原子状态 {
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;
}
}
下面是我试过的一段代码。每个文件都有一个整数,我想将所有整数相加并显示输出
@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 方法时,都会使用阻塞队列中的值进行更新。
我已经隔离并创建了一个单例 class,其中 returns 我在请求时为每个线程使用相同的原子整数对象。
下面是代码片段,这解决了我的问题 -
导入java.util.concurrent.atomic.AtomicInteger;
public class 原子状态 {
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;
}
}