等待线程池中任务执行完成
程序员文章站
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
上一篇: IOC创建对象的四种方式