简体   繁体   中英

Java ExecutorService pulls tasks all at once

This question is about Java Concurrency. I'm trying to get cmdline to execute another application that takes cmdline arguments in Windows 10 and Server 2012R2. Basically I am trying run the program against 5 files at a time (threadpool is 5). The problem is, I can't get Java to not have more than 5 instances of that application running at a time. It will bassically try and start an instance for every file at one time if not for the Thread.sleep method.

The program i'm trying to launch does return output in cmdline and powershell (I tried that too), so I tried to trick Java into waiting for the instance to fully complete with text and a java.isAlive loop within the lambda, so the process would only finish the lambda once the process self terminates after processing the file it was assigned. None of that worked.

Do I have to write "Process process = Runtime.getRuntime()" within the lambda in a seperate class and create a new object in the lambda instead with the arguments? Any ideas?

                ExecutorService service = Executors.newFixedThreadPool(5);
                File file = new File("SCAP_Hosts/");
                File[] f = file.listFiles();
                for (File x : f) {
                    String y = x.toString();
                    Future<?> result = service.submit(() -> {
                        Process process = Runtime.getRuntime().exec("c:/Software/SCAP Compliance Checker 5.0.2/cscc.exe -o WSoptions.xml -f " + y);
                        try {
                            Thread.sleep(60000);
                            x.delete();
                            } catch (IOException | InterruptedException e) {e.printStackTrace();}
                    });
                    try {Thread.sleep(20000);} catch (InterruptedException e) {e.printStackTrace();}
                }
            } 
            }
            service.shutdown();
            while (true) {
                if (service.isTerminated()) {
                    System.out.println("Program Finished");
                    break;

You did not call any blocking method on Process so the thread does not have to wait for anything and just marks itself ready for a next task.

I suggest you call process.waitFor()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM