【并发编程】- 线程池使用方法allowCoreThreadTimeOut设置核心线程超时

462 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第24天,点击查看活动详情

线程池使用方法allowCoreThreadTimeOut(boolean value)设置核心线程超时

方法allowsCoreThreadTimeOut()和allowCoreThreadTimeOut(boolean value)的作用是配置核心线程是否有超时的效果。

线程执行代码如下:

public class FirstRunnable implements Runnable {


    @Override
    public void run() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
        try {
            System.out.println(Thread.currentThread().getName() +"  开始时间:"+simpleDateFormat.format(new Date()));
            Thread.sleep(1000);
            System.out.println(Thread.currentThread().getName() +"  结束时间:"+simpleDateFormat.format(new Date()));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

运行类代码如下:

public class AllowsCoreThreadTimeOutRun {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4, 6, 6, TimeUnit.SECONDS, new SynchronousQueue<>());
        System.out.println("是否设置核心线程超时:"+threadPoolExecutor.allowsCoreThreadTimeOut());
        for (int i = 0; i < 4; i++) {
            FirstRunnable firstRunnable = new FirstRunnable();
            threadPoolExecutor.execute(firstRunnable);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程池存活线程数:"+threadPoolExecutor.getPoolSize());
    }
}

运行结果如下:

是否设置核心线程超时:false
pool-1-thread-1  开始时间:16:27:19
pool-1-thread-3  开始时间:16:27:19
pool-1-thread-2  开始时间:16:27:19
pool-1-thread-4  开始时间:16:27:19
线程池存活线程数:4
pool-1-thread-2  结束时间:16:27:20
pool-1-thread-4  结束时间:16:27:20
pool-1-thread-1  结束时间:16:27:20
pool-1-thread-3  结束时间:16:27:20

修改运行类启用设置核心线程超时

public class AllowsCoreThreadTimeOutRun {
    public static void main(String[] args) {
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(4, 6, 6, TimeUnit.SECONDS, new SynchronousQueue<>());
        threadPoolExecutor.allowCoreThreadTimeOut(true);
        System.out.println("是否设置核心线程超时:"+threadPoolExecutor.allowsCoreThreadTimeOut());
        for (int i = 0; i < 4; i++) {
            FirstRunnable firstRunnable = new FirstRunnable();
            threadPoolExecutor.execute(firstRunnable);
        }
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程池存活线程数:"+threadPoolExecutor.getPoolSize());
    }
}

运行结果如下:

是否设置核心线程超时:true
pool-1-thread-3  开始时间:16:36:03
pool-1-thread-1  开始时间:16:36:03
pool-1-thread-4  开始时间:16:36:03
pool-1-thread-2  开始时间:16:36:03
pool-1-thread-2  结束时间:16:36:04
pool-1-thread-3  结束时间:16:36:04
pool-1-thread-4  结束时间:16:36:04
pool-1-thread-1  结束时间:16:36:04
线程池存活线程数:0