ThreadPoolExecutor线程池的销毁需要注意以下几点:
1. 调用shutdown()方法
调用ThreadPoolExecutor的shutdown()方法可以平缓地关闭线程池,即不再接受新任务,但会等待已经提交的任务执行完毕后再关闭线程池。
```
executor.shutdown();
```
2. 调用shutdownNow()方法
调用ThreadPoolExecutor的shutdownNow()方法可以立即关闭线程池,即不再接受新任务,并尝试中断正在执行的任务。
```
executor.shutdownNow();
```
3. 等待线程池关闭
在调用shutdown()或shutdownNow()方法后,可以通过调用awaitTermination()方法等待线程池关闭。该方法会阻塞当前线程,直到线程池关闭或超时。
```
executor.shutdown();
try {
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
executor.shutdownNow();
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
System.err.println("线程池未正常关闭");
}
}
} catch (InterruptedException e) {
executor.shutdownNow();
Thread.currentThread().interrupt();
}
```
完整示例代码如下:
```
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPoolDemo {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
// 提交任务
for (int i = 0; i < 100; i++) {
executor.submit(new Task());
}
// 关闭线程池
executor.shutdown();
try {
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
executor.shutdownNow();
if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
System.err.println("线程池未正常关闭");
}
}
} catch (InterruptedException e) {
executor.shutdownNow();
Thread.currentThread().interrupt();
}
}
static class Task implements Runnable {
@Override
public void run() {
// 任务逻辑
}
}
}
```