Executor 在 main 中运行后如何完成我的程序

How to finish my program after Executor runs in main

我在完成主线程时遇到问题。当线程"finish"时(也许不是,我不知道,但我在静态变量"nextNumber"中得到了正确的结果),程序仍然有效。

我想 Executor 没有终止是因为他还在等待另一个线程 运行。

早些时候我使用了自己的 运行nable class 并且没有注意终止它。

我的代码:

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);
}

首先你需要使用ExecutorService然后你需要关闭它。

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