awaitTermination() shutdown()

论坛 期权论坛 脚本     
匿名技术用户   2021-1-5 11:02   558   0

newFixedThreadPool

创建一个固定大小的线程池。

shutdown():用于关闭启动线程,如果不调用该语句,jvm不会关闭。

awaitTermination():用于等待子线程结束,再继续执行下面的代码。该例中我设置一直等着子线程结束。

Java代码 复制代码 收藏代码
  1. public class Test {
  2. public static void main(String[] args) throws IOException, InterruptedException {
  3. ExecutorService service = Executors.newFixedThreadPool(2);
  4. for (int i = 0; i < 4; i++) {
  5. Runnable run = new Runnable() {
  6. @Override
  7. public void run() {
  8. System.out.println("thread start");
  9. }
  10. };
  11. service.execute(run);
  12. }
  13. service.shutdown();
  14. service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
  15. System.out.println("all thread complete");
  16. }
  17. }
public class Test {

 public static void main(String[] args) throws IOException, InterruptedException {
  ExecutorService service = Executors.newFixedThreadPool(2);
  for (int i = 0; i < 4; i++) {
   Runnable run = new Runnable() {
    @Override
    public void run() {
     System.out.println("thread start");
    }
   };
   service.execute(run);
  }
  service.shutdown();
  service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
  System.out.println("all thread complete");
 }
}

输出:
thread start
thread start
thread start
thread start
all thread complete
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP