注意: 一定要将线程回收,否则程序会一直等待!! 也可以关闭线程池,来退出程序,但是这样会导致新的任务无法执行!!
线程回收之后,有新的任务到来就会自动新建线程。
线程回收之后,有新的任务到来就会自动新建线程。
class Task implements Runnable
{
private int x; //线程编号
public Task(int x) {
this.x = x;
}
public void run() {
System.out.println(x + " thread doing something!");
System.out.println("第" + x + "个线程执行完毕");
}
}
1、设置线程池线程最大空闲时间,超出这个时间,对线程进行回收
不回收效果(程序一直等待,不退出):
public static void main(String[] args) throws InterruptedException {
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
5, 5,
1, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10, false),
new ThreadPoolExecutor.CallerRunsPolicy()
);
for (int i = 1; i <= 5; i++) {
threadPool.execute(new Task(i));
}
}
回收效果:
public static void main(String[] args) throws InterruptedException {
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
5, 5,
1, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10, false),
new ThreadPoolExecutor.CallerRunsPolicy()
);
threadPool.allowCoreThreadTimeOut(true); //线程的最大空闲时间,超出这个时间将进行回收
for (int i = 1; i <= 5; i++) {
threadPool.execute(new Task(i));
}
}
2、关闭线程池(关闭之后,有新任务却不会执行)
public static void main(String[] args) throws InterruptedException {
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
5, 5,
1, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10, false),
new ThreadPoolExecutor.CallerRunsPolicy()
);
for (int i = 1; i <= 5; i++) {
threadPool.execute(new Task(i));
}
threadPool.shutdown();
try {
//Thread.sleep(10*1000);
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 6; i <= 10; i++) {
threadPool.execute(new Task(i));
}
}