java线程池线程回收

本文探讨了Java线程池中如何设置线程的最大空闲时间以实现线程回收,以及如何关闭线程池,确保在关闭后不再执行新任务。通过实例展示了不回收线程时程序可能的等待状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意: 一定要将线程回收,否则程序会一直等待!! 也可以关闭线程池,来退出程序,但是这样会导致新的任务无法执行!!
线程回收之后,有新的任务到来就会自动新建线程。
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));
        }
    }


 

 

 


 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值