关闭线程池的shutdown方法
关闭线程池后,不再接受新的任务
public class Task implements Runnable{
private final int index;
public Task(int index){
this.index = index;
}
public void run() {
System.out.println(Thread.currentThread().getName()+" "+index);
}
}
import com.naidou.threadPool.tp06.Task;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPool07 {
public static void main(String[] args) {
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1,1,0L, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(1),
new ThreadPoolExecutor.AbortPolicy());
try {
threadPool.execute((new Task(1)));
}catch (RejectedExecutionException e){
e.printStackTrace();
} finally {
threadPool.shutdown();
threadPool.execute(new Task(2));
}
}
}
- 输出结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d99b2f95365b2210d98c22bc9ba33c01.png)
关闭线程池后,会继续执行完任务队列中的任务
import com.naidou.threadPool.tp06.Task;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPool07 {
public static void main(String[] args) {
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1,1,0L, TimeUnit.SECONDS,new LinkedBlockingQueue<Runnable>(1),
new ThreadPoolExecutor.AbortPolicy());
try {
threadPool.execute((new Task(1)));
threadPool.execute((new Task(3)));
}catch (RejectedExecutionException e){
e.printStackTrace();
} finally {
threadPool.shutdown();
threadPool.execute(new Task(2));
}
}
}
- 输出结果:
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8280db75e7987b213775d2260ce11411.png)
参考地址:
线程池视频08