Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4468410
  • 博文数量: 1214
  • 博客积分: 13195
  • 博客等级: 上将
  • 技术积分: 9105
  • 用 户 组: 普通用户
  • 注册时间: 2007-01-19 14:41
个人简介

C++,python,热爱算法和机器学习

文章分类

全部博文(1214)

文章存档

2021年(13)

2020年(49)

2019年(14)

2018年(27)

2017年(69)

2016年(100)

2015年(106)

2014年(240)

2013年(5)

2012年(193)

2011年(155)

2010年(93)

2009年(62)

2008年(51)

2007年(37)

分类: Java

2018-09-13 12:44:58

https://blog.csdn.net/wo541075754/article/details/51564359

ExecutorService的关闭

shutdown和awaitTermination为接口ExecutorService定义的两个方法,一般情况配合使用来关闭线程池。

方法简介

  1. shutdown方法:平滑的关闭ExecutorService,当此方法被调用时,ExecutorService停止接收新的任务并且等待已经提交的任务(包含提交正在执行和提交未执行)执行完成。当所有提交任务执行完毕,线程池即被关闭。

  2. awaitTermination方法:接收人timeout和TimeUnit两个参数,用于设定超时时间及单位。当等待超过设定时间时,会监测ExecutorService是否已经关闭,若关闭则返回true,否则返回false。一般情况下会和shutdown方法组合使用。

具体实例

普通任务处理类:

package com.secbro.test.thread; import java.util.concurrent.Callable; /**
 * @author zhuzhisheng
 * @Description * @date on 2016/6/1.
 */ public class Task implements Callable{ @Override public Object call() throws Exception {
        System.out.println("普通任务"); return null;
    }
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

长时间任务处理类:

package com.secbro.test.thread; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; /**
 * @author zhuzhisheng
 * @Description * @date on 2016/6/1.
 */ public class LongTask implements Callable{ @Override public Object call() throws Exception {
        System.out.println("长时间任务");
        TimeUnit.SECONDS.sleep(5); return null;
    }
} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

测试类:

package com.secbro.test.thread; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /**
 * @author zhuzhisheng
 * @Description * @date on 2016/6/1.
 */ public class TestShutDown { public static void main(String[] args) throws InterruptedException{
        ScheduledExecutorService service = Executors.newScheduledThreadPool(4);

        service.submit(new Task());
        service.submit(new Task());
        service.submit(new LongTask());
        service.submit(new Task());


        service.shutdown(); while (!service.awaitTermination(1, TimeUnit.SECONDS)) {
            System.out.println("线程池没有关闭");
        }

        System.out.println("线程池已经关闭");
    }

} 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

输出结果为:

普通任务
普通任务
长时间任务
普通任务
线程池没有关闭
线程池没有关闭
线程池没有关闭
线程池没有关闭
线程池已经关闭
阅读(1049) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~