Java线程池的状态共有五种,它们分别是:
RUNNING:运行状态,这是线程池的初始状态,能够接受新任务和处理已添加的任务。
SHUTDOWN:关闭状态,调用线程池的
shutdown()
方法会使线程池进入该状态。线程池不再接受新任务,但会继续处理阻塞队列中的任务。STOP:停止状态,调用线程池的
shutdownNow()
方法会使线程池进入该状态。线程池不再接受新任务,也不会处理阻塞队列中的任务,并且会尝试中断正在执行的任务。TIDYING:整理状态,当所有任务都已终止,线程池会进入该状态。
terminated()
钩子方法会被很快调用。TERMINATED:销毁状态,执行Terminated()方法。这是一个钩子方法,以便我们可以在ThreadPool终止时进行一些处理。 以上这些状态的变化过程是顺序的,即一个状态结束后,线程池会进入下一个状态,直到最终达到 TERMINATED 状态。
创建线程池的方法
1. 使用 Executors 创建线程
阿里巴巴开发手册并不推荐用这种方法,如果你自己测试的时候倒是可以快速使用一下。
public class ThreadPoolExample {
public static void main(String[] args) {
// 创建固定大小的线程池
ExecutorService executorService = Executors.newFixedThreadPool(4);
// 提交任务到线程池
for (int i = 0; i < 10; i++) {
final int taskId = i;
executorService.execute(() -> {
System.out.println("Running task " + taskId + " on thread " + Thread.currentThread().getName());
// 执行任务相关的代码
});
}
// 关闭线程池
executorService.shutdown();
}
}
2.使用 ThreadPoolExecutor 创建
public class CustomThreadPoolExample {
public static void main(String[] args) {
// 创建自定义线程池
ThreadPoolExecutor executor = new ThreadPoolExecutor(
2, // 核心线程数
4, // 最大线程数
60, // 线程空闲时间
TimeUnit.SECONDS, // 线程空闲时间单位
new ArrayBlockingQueue<>(10) // 任务队列
);
// 提交任务和关闭线程池的代码与上面的例子相同
}
}
上面代码中我提交任务使用的是 execute() ,也可以用 submit() 。这两个区别就在于在于 execute 只是简单地启动任务,而 submit 返回一个 Future 对象来管理任务。
如果使用 submit 可以实现下面的代码
public class Main {
public static void main(String[] args) {
// 创建固定大小的线程池
ExecutorService executorService = Executors.newFixedThreadPool(4);
// 提交任务到线程池
for (int i = 0; i < 10; i++) {
final int taskId = i;
Future<?> submit = executorService.submit(() -> {
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Running task " + taskId + " on thread " + Thread.currentThread().getName());
// 执行任务相关的代码
});
// 如果 i == 2 则取消掉这个线程
if (i == 2) {
submit.cancel(true);
}
}
// 关闭线程池
executorService.shutdown();
}
}
结果就变成了
// 其中的 task 2 被干掉了
Running task 4 on thread pool-1-thread-3
Running task 3 on thread pool-1-thread-4
Running task 1 on thread pool-1-thread-2
Running task 0 on thread pool-1-thread-1
Running task 5 on thread pool-1-thread-3
Running task 6 on thread pool-1-thread-4
Running task 8 on thread pool-1-thread-1
Running task 7 on thread pool-1-thread-2
Running task 9 on thread pool-1-thread-3
评论区