Java 示例代码中的Shutdown()方法

Java 示例代码中的Shutdown()方法,java,Java,下面列出了我找到的使用java.util.concurrent.ExecutorService的示例代码。主类包括一个shutdown()方法,该方法调用ExecutorService上的shutdown()方法。从这个例子中我不理解的是何时调用这个方法 谢谢 package multithreadingexample; import java.io.IOException; import java.util.concurrent.ExecutorService; import java.uti

下面列出了我找到的使用java.util.concurrent.ExecutorService的示例代码。主类包括一个shutdown()方法,该方法调用ExecutorService上的shutdown()方法。从这个例子中我不理解的是何时调用这个方法

谢谢

package multithreadingexample;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class MultithreadingExample {

    ExecutorService executor = Executors.newFixedThreadPool(3);

    public void start() throws IOException {
        int i=0;
        while (!executor.isShutdown())
            executor.submit(new MyThread(i++));
    }

    public void shutdown() throws InterruptedException {
        executor.shutdown();
        executor.awaitTermination(30, TimeUnit.SECONDS);
        executor.shutdownNow();
    }

    public static void main(String argv[]) throws Exception {
        new MultithreadingExample().start();
    }
}
class MyThread implements Runnable {
    private final int i;

    MyThread(int i) {
        this.i = i;
    }

    @Override
    public void run() {
        System.out.println("I am in thread:"+i);    
    }

}
为什么会这样: 提供一种关闭ExecutorService的方法,以停止它运行任务并释放它正在使用的线程

如何称呼它: 您需要在使用Executor服务后调用它。在您提供的示例代码中,不会在任何地方调用它

从:

shutdown()方法将允许执行以前提交的任务 在终止之前,当shutdownNow()方法阻止等待时 无法启动任务并尝试停止当前正在执行的任务


只是想澄清一下我的问题:我理解multi-threadingexample.shutdown()的功能,但我不明白它为什么会出现,或者它是如何被调用的。谢谢。您必须在主方法中调用它。您需要在希望程序停止时调用它,否则线程池中的线程将继续运行,JVM将不会停止。谢谢。我担心可能有一些我不理解的隐式调用。对于那些可能感兴趣的人,示例代码取自此处: