Skip to content

Instantly share code, notes, and snippets.

@shiguruikai
Created April 17, 2021 16:14
Show Gist options
  • Save shiguruikai/e8f53e7eb5db568cc5ddb8039059259b to your computer and use it in GitHub Desktop.
Save shiguruikai/e8f53e7eb5db568cc5ddb8039059259b to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ParallelExecutor {
public static void main(String[] args) {
int nThreads = Integer.parseInt(args[0]);
if (nThreads <= 0) {
nThreads = Runtime.getRuntime().availableProcessors();
}
ExecutorService threadPool = Executors.newFixedThreadPool(nThreads);
Stream<String> commands =
args.length > 1
? Arrays.stream(args).skip(1)
: new Scanner(System.in).useDelimiter(System.lineSeparator()).tokens();
try {
commands
.map(
command ->
threadPool.submit(
() ->
new ProcessBuilder("cmd.exe", "/c", command)
.inheritIO()
.start()
.waitFor()))
.collect(Collectors.toList())
.forEach(
it -> {
try {
it.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
});
} finally {
threadPool.shutdownNow();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment