温馨提示×

java怎么判断线程池是否执行完毕

小亿
131
2023-08-20 03:36:47
栏目: 编程语言

在Java中,可以使用ExecutorService来创建线程池,然后利用isTerminated()方法来判断线程池是否执行完毕。

下面是一个示例代码:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) {
// 创建线程池
ExecutorService executor = Executors.newFixedThreadPool(3);
// 提交任务
for (int i = 0; i < 5; i++) {
executor.submit(new Task(i));
}
// 关闭线程池
executor.shutdown();
// 等待所有任务执行完毕
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 判断线程池是否执行完毕
if (executor.isTerminated()) {
System.out.println("线程池执行完毕");
} else {
System.out.println("线程池还在执行中");
}
}
static class Task implements Runnable {
private int id;
public Task(int id) {
this.id = id;
}
@Override
public void run() {
System.out.println("任务 " + id + " 正在执行");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("任务 " + id + " 执行完毕");
}
}
}

在上面的示例中,我们创建了一个固定大小为3的线程池,并提交了5个任务。然后使用awaitTermination()方法等待所有任务执行完毕,并使用isTerminated()方法判断线程池是否执行完毕。

运行示例代码,输出结果为:

任务 0 正在执行
任务 1 正在执行
任务 2 正在执行
任务 0 执行完毕
任务 3 正在执行
任务 1 执行完毕
任务 4 正在执行
任务 2 执行完毕
任务 3 执行完毕
任务 4 执行完毕
线程池执行完毕

可以看到,当所有任务执行完毕后,输出了"线程池执行完毕"的提示。

0