`
ncs123
  • 浏览: 99931 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

shutdown,awaitTermination使用

    博客分类:
  • J2SE
阅读更多
1.shutdown方法:这个方法会平滑地关闭ExecutorService,当我们调用这个方法时,ExecutorService停止接受任何新的任务且等待已经提交的任务执行完成(已经提交的任务会分两类:一类是已经在执行的,另一类是还没有开始执行的),当所有已经提交的任务执行完毕后将会关闭ExecutorService。

2.awaitTermination方法:这个方法有两个参数,一个是timeout即超时时间,另一个是unit即时间单位。这个方法会使线程等待timeout时长,当超过timeout时间后,会监测ExecutorService是否已经关闭,若关闭则返回true,否则返回false。一般情况下会和shutdown方法组合使用。(awaitTermination不会关闭ExecutorService,只是定时检测一下他是否关闭)

public static void main(String[] args) throws IOException, InterruptedException {
		ExecutorService service = Executors.newFixedThreadPool(3);
		for (int i = 0; i < 4; i++) {
			Runnable run = new Runnable() {
				@Override
				public void run() {
					try {
						Thread.sleep(4000);
					} catch (InterruptedException e) {
						Thread.currentThread().interrupt();
					}
					System.out.println("thread start");
				}
			};
			service.execute(run);
		}
		service.shutdown();
		while(!service.awaitTermination(2, TimeUnit.SECONDS)){
			System.out.println("service not stop");
		}
		System.out.println("all thread complete");
	}


运行结果:
  service not stop
  thread start
  thread start
  thread start
  service not stop
  service not stop
  thread start
  all thread complete
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics