-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDoWorkParallel.java
More file actions
executable file
·53 lines (49 loc) · 1.83 KB
/
Copy pathDoWorkParallel.java
File metadata and controls
executable file
·53 lines (49 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// Do work parallel.
// read command(every line) from stdin.
import java.io.*;
import java.util.concurrent.*;
public class DoWorkParallel {
public static void main(String[] args) {
if (args.length < 1) {
throw new IllegalArgumentException("Need parallel number.");
}
WorkManager workManager = new WorkManager(Integer.parseInt(args[0]));
String command;
try (BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) {
while ((command = stdIn.readLine()) != null) {
workManager.AddCommand(command);
}
} catch (IOException e) {
e.printStackTrace(System.err);
}
workManager.waitStop();
}
}
class WorkManager {
ExecutorService executorService;
WorkManager(int parallelNumber) {
executorService = Executors.newFixedThreadPool(parallelNumber);
}
void AddCommand(final String command) {
executorService.submit(new Runnable(){
public void run() {
try {
ProcessBuilder pb = new ProcessBuilder("bash", "-c", command);
pb.redirectErrorStream(true);
pb.redirectOutput(ProcessBuilder.Redirect.appendTo(new java.io.File("/dev/stdout")));
System.out.println("Return code: " + pb.start().waitFor() + " " + command);
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
});
}
void waitStop() {
executorService.shutdown();
try {
executorService.awaitTermination(99999999L, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
}
}