简体   繁体   中英

ScheduledExecutorService not working as expected

On executing the following code, the statement System.out.println("completed"); gets executed before the executor even though delay is set to 0. Why is it so? How can the order be maintained here?

public class TestMyClass {
    private static int count = 0;

    public static void main(String args[]) {
        ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();

        Runnable periodicTask = () -> {
            try {
                List<String> lines = Files.readAllLines(new File("E:\\MyFile.log").toPath());
                String key = "FIND ME";
                System.out.println("text not found");
                for (String line : lines) {
                    if (line.contains(key)) {
                        count++;
                        System.out.println("found text ..." + count);
                        executor.shutdown();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        };

        executor.scheduleAtFixedRate(periodicTask, 0, 5, TimeUnit.SECONDS);
        System.out.println("completed");
    }
}

Checking the condition while(.executor.isTerminated()) does the job. It ensures the next statements are executed only after the executor has done its job.

The reason is in the nature of multi-tasking/threading. The ScheduledExecutorService starts a new thread that executes your Runnable . Independently from that your main program continues its work in its own/original thread.

Both threads, the main and the runnable, will be processed in parallel.

In your case, the System.out.println("completed"); is faster in the execution then the Runnable that reads a file.

Now it depends on what you want to achieve. As you wrote already you can block your main program, eg with a loop and wait for the executor to finish all execution. But this is not what you usually do because then you could just execute the code in the same thread.

Typically you use multi-threading to execute code in parallel or to not block a task/thread, eg calling an web service and continue to do some other stuff.

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