欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-19 11:21:34
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 voi...

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

本文地址:https://blog.csdn.net/qq_33398607/article/details/111901538

相关标签: Java基础