Use thread pools (ExecutorService)
parent
a035067f80
commit
972c5de903
@ -0,0 +1,32 @@
|
|||||||
|
package multi.threading.using.thread.pools;
|
||||||
|
|
||||||
|
import java.io.BufferedReader;
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Paths;
|
||||||
|
import java.util.concurrent.Callable;
|
||||||
|
|
||||||
|
public class Adder implements Callable<Integer> {
|
||||||
|
private final String inFile;
|
||||||
|
|
||||||
|
public Adder(String inFile) {
|
||||||
|
this.inFile = inFile;
|
||||||
|
}
|
||||||
|
|
||||||
|
public int doAdd() throws IOException {
|
||||||
|
int total = 0;
|
||||||
|
String line;
|
||||||
|
|
||||||
|
try (BufferedReader reader = Files.newBufferedReader(Paths.get(inFile))) {
|
||||||
|
while ((line = reader.readLine()) != null)
|
||||||
|
total += Integer.parseInt(line);
|
||||||
|
}
|
||||||
|
|
||||||
|
return total;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Integer call() throws IOException {
|
||||||
|
return doAdd();
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,34 @@
|
|||||||
|
package multi.threading.using.thread.pools;
|
||||||
|
|
||||||
|
import java.util.concurrent.*;
|
||||||
|
|
||||||
|
public class Main {
|
||||||
|
private static final String rootResources = "C:\\Users\\sgoud\\JavaProjects\\Learning-Java\\Pluralsite\\src\\intermediate\\Java Fundamentals - The Core Platform\\resources\\threading\\";
|
||||||
|
|
||||||
|
public static void main(String[] args) throws InterruptedException, ExecutionException {
|
||||||
|
String[] inFiles = {
|
||||||
|
rootResources + "inputFile1.txt",
|
||||||
|
rootResources + "inputFile2.txt",
|
||||||
|
rootResources + "inputFile3.txt",
|
||||||
|
rootResources + "inputFile4.txt",
|
||||||
|
rootResources + "inputFile5.txt",
|
||||||
|
rootResources + "inputFile6.txt"
|
||||||
|
};
|
||||||
|
ExecutorService executorService = Executors.newFixedThreadPool(3);
|
||||||
|
Future[] results = new Future[inFiles.length];
|
||||||
|
|
||||||
|
for(int i=0; i < inFiles.length; i++) {
|
||||||
|
Adder adder = new Adder(inFiles[i]);
|
||||||
|
results[i] = executorService.submit(adder);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (Future<Integer> result : results) {
|
||||||
|
System.out.println(result.get());
|
||||||
|
}
|
||||||
|
|
||||||
|
executorService.shutdown();
|
||||||
|
if (executorService.awaitTermination(60, TimeUnit.SECONDS)) {
|
||||||
|
System.out.println("Operations Executed Successfully!");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue