在Java中,线程池的状态主要包括RUNNING
(运行)、SHUTDOWN
(关闭)、STOP
(停止)和TIDYING
(整理)等。这些状态由ThreadPoolExecutor
类中的ctl
字段管理,ctl
字段的高3位表示线程池的状态,低29位表示线程的数量。以下是线程池的几种状态:
RUNNING(运行):
shutdown()
方法时,会切换到SHUTDOWN
状态。SHUTDOWN(关闭):
shutdown()
方法后,线程池会拒绝新任务,但会继续处理已经提交的任务。STOP(停止):
shutdownNow()
方法后,线程池会拒绝新任务,并尝试停止所有正在执行的任务。TIDYING(整理):
TERMINATED(终止):
以下是一个简单的示例,演示了如何使用线程池,并获取线程池的状态:
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadPoolExample {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(2);
// 获取线程池状态
System.out.println("线程池状态: " + getThreadPoolStatus(executorService));
// 提交任务
executorService.submit(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Task 1 executed");
});
// 提交任务
executorService.submit(() -> System.out.println("Task 2 executed"));
// 关闭线程池
executorService.shutdown();
// 获取线程池状态
System.out.println("线程池状态: " + getThreadPoolStatus(executorService));
}
private static String getThreadPoolStatus(ExecutorService executorService) {
if (executorService instanceof ThreadPoolExecutor) {
ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executorService;
int state = threadPoolExecutor.getRunState();
switch (state) {
case -1:
return "TERMINATED";
case 0:
return "RUNNING";
case 1:
return "SHUTDOWN";
case 2:
return "STOP";
case 3:
return "TIDYING";
default:
return "Unknown State";
}
} else {
return "Not a ThreadPoolExecutor";
}
}
}
在这个示例中,创建了一个固定大小的线程池,提交了两个任务后,关闭了线程池,并通过getThreadPoolStatus
方法获取线程池的状态。