怎样正常结束ExecutorPool

 

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main {

static ExecutorService exec = Executors.newFixedThreadPool(5);

public static void main(String argc[]) {
for (int i = 0; i < 100; i++) {
exec.submit(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 10; i++) {
int a = 10;
int b = 12;
a = a + b;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("finish");
}
});
}
exec.shutdown();
try {
exec.awaitTermination(1000, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("ok");
}
}

程序结束前,Executor需要清理,否则JVM无法争创关闭,会被挂起。一旦Executor清理后就无法在接受新任务了。

正常的步骤是:

1、提交所有任务

2、executor.shutdown()

3、awaitTermination(timeout)

4、当时间到或者所有任务都完成后,结束,JVM也可以结束。

再次强调,线程池自动是可复用的。这个只是为了退出程序前的清理

Leave a Reply

Your email address will not be published. Required fields are marked *