【并发编程】- 线程池使用shutdown()方法中断任务

108 阅读2分钟

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

方法shutdown()和shutdownNow()与返回值

线程池使用方法shutdown(),停止线程池,实现代码如下:

public class ShutdownRun {
    public static void main(String[] args) {
        FirstRunnable firstRunnable = new FirstRunnable();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 6, 0, TimeUnit.SECONDS,new LinkedBlockingQueue<>());
        threadPoolExecutor.execute(firstRunnable);
        threadPoolExecutor.shutdown();
        System.out.println("main end");
    }
}

运行结果如下:

pool-1-thread-1  开始时间:1654590959357
main end
pool-1-thread-1  结束时间:1654590961363

从运行结果看出2秒后进程结束。

修改执行任务数如下:

public class ShutdownRun {
    public static void main(String[] args) {
        FirstRunnable firstRunnable = new FirstRunnable();
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5, 6, 100, TimeUnit.SECONDS,new LinkedBlockingQueue<>());
        for (int i = 0; i < 8 ; i++) {
            threadPoolExecutor.execute(firstRunnable);
        }
        threadPoolExecutor.shutdown();
        threadPoolExecutor.execute(firstRunnable);
        System.out.println("main end");
    }
}

运行结果如下:

pool-1-thread-1  开始时间:1654675734896
pool-1-thread-3  开始时间:1654675734897
pool-1-thread-2  开始时间:1654675734897
pool-1-thread-4  开始时间:1654675734899
pool-1-thread-5  开始时间:1654675734900
Exception in thread "main" java.util.concurrent.RejectedExecutionException: Task com.ozx.concurrentprogram.executor.service.FirstRunnable@44e81672 rejected from java.util.concurrent.ThreadPoolExecutor@60215eee[Shutting down, pool size = 5, active threads = 5, queued tasks = 3, completed tasks = 0]
	at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2063)
	at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:830)
	at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1379)
	at com.ozx.concurrentprogram.executor.controller.ShutdownRun.main(ShutdownRun.java:23)
pool-1-thread-3  结束时间:1654675736905
pool-1-thread-2  结束时间:1654675736905
pool-1-thread-1  结束时间:1654675736906
pool-1-thread-2  开始时间:1654675736907
pool-1-thread-1  开始时间:1654675736907
pool-1-thread-3  开始时间:1654675736907
pool-1-thread-5  结束时间:1654675736908
pool-1-thread-4  结束时间:1654675736908
pool-1-thread-1  结束时间:1654675738919
pool-1-thread-2  结束时间:1654675738919
pool-1-thread-3  结束时间:1654675738919

从运行结果看出执行了8个任务,最后一个任务报异常,因为执行了shutdown()方法,并且当前进程销毁。

任务执行代码如下:

public class SecondRunnable implements Runnable {


    @Override
    public void run() {
        try {
        for (int i = 0; i < Integer.MAX_VALUE / 10; i++) {
                if (Thread.currentThread().isInterrupted() == true) {
                    System.out.println("任务没有完成,就被中断了!");
                    throw new InterruptedException();
                }
        }
        } catch (InterruptedException e) {
            System.out.println("进入catch中断了任务");
            e.printStackTrace();
        }
    }
}