Search code examples
javamultithreadingterminateexecutor

How to finish my program after Executor runs in main


I have a problem with finishing my main thread. When threads "finish" (maybe not, I don't know, but I have a right result in static variable "nextNumber"), the program still works.

I suppose that the Executor doesn't terminate because he still waits for another threads to run.

Earlier I used my own runnable class and hadn't to take care about terminating it.

My code:

private static long nextNumber = 0;

public static void main(String[] args) {
    Runnable firstCounter = () -> {
        for (int i = 0; i < 1000000; i++)
            increment("Thread 1");
    };

    Runnable secondCounter = () -> {
        for (int i = 0; i < 1000000; i++)
            increment("Thread 2");
    };

    Executor executor = Executors.newFixedThreadPool(2);
    executor.execute(firstCounter);
    executor.execute(secondCounter);

    System.out.println(nextNumber);
}

synchronized private static void increment(String threadName) {
    System.out.println(threadName + " " + ++nextNumber);
}

Solution

  • First you need to use ExecutorService and then you need to shut it down.

    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.shutdown(); //Prevents executor from accepting new tasks
    executor.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS); //Waits until currently executing tasks finish but waits not more then specified amount of time