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

Java Executor在main中运行后如何完成我的程序,java,multithreading,terminate,executor,Java,Multithreading,Terminate,Executor,我在完成主线时遇到问题。当线程“finish”(也许不是,我不知道,但我在静态变量“nextNumber”中有一个正确的结果)时,程序仍然工作 我认为执行器不会终止,因为他仍在等待另一个线程运行 早些时候,我使用了自己的runnable类,没有考虑终止它 我的代码: private static long nextNumber = 0; public static void main(String[] args) { Runnable firstCounter = () -> {

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

我认为执行器不会终止,因为他仍在等待另一个线程运行

早些时候,我使用了自己的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);
}
private static long nextNumber=0;
公共静态void main(字符串[]args){
可运行的firstCounter=()->{
对于(int i=0;i<1000000;i++)
增量(“螺纹1”);
};
可运行的第二个计数器=()->{
对于(int i=0;i<1000000;i++)
增量(“螺纹2”);
};
Executor Executor=Executors.newFixedThreadPool(2);
执行人。执行(第一计数器);
执行人执行(第二计数器);
System.out.println(下一个编号);
}
同步私有静态无效增量(字符串threadName){
System.out.println(threadName+++++nextNumber);
}

首先需要使用执行器服务,然后需要将其关闭

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

您可能想看看线程是“守护进程”还是非守护进程。