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

时间:2018-03-06 21:30:10

标签: java multithreading terminate executor

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

我认为Executor没有终止,因为他仍在等待另一个线程运行。

之前我使用过自己的runnable类,并没有注意终止它。

我的代码:

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

1 个答案:

答案 0 :(得分:2)

首先,您需要使用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