等待线程池中任务执行完成

Callable Task本身返回Feature可判断isDone(),在此不赘述。

测试 ThreadPoolExecutor 线程池submit无返回值的Runnable task也可返回Feature判断isDone()

package com.example.test;

import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

public class t1 {
  @Test
  public void test1() {
    ThreadPoolExecutor pool =
        new ThreadPoolExecutor(
            2,
            4,
            0,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(),
            Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.AbortPolicy());

    Future<?> submit = pool.submit(new MyTask());
    while (!submit.isDone()) {
      System.out.println(submit.isDone());
    }
    System.out.println(submit.isDone());
  }

  private class MyTask implements Runnable {

    @Override
    public void run() {
      try {
        Thread.sleep(10000);
        System.out.println("task1 completed");
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }
}

结果:

...
false
false
task1 completed
false
false
false
true
# 10s44ms

你可能感兴趣的:(Java基础)