package com.neutron.t23;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* 线程池接口
* 了解线程池
*/
public class T235ThreadPool {
public static void main(String[] args) throws InterruptedException {
// 创建固定大小为5的线程池,线程池都实现ExecutorService接口
ExecutorService service = Executors.newFixedThreadPool(5);
for (int i = 0; i < 6; i++) {
// 向ExecutorService可以扔Callable或Runnable类型的任务
service.execute(() -> {
try {
TimeUnit.MILLISECONDS.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
});
}
/*
java.util.concurrent.ThreadPoolExecutor@568db2f2
[Running, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
Running表示线程池状态
pool size = 5表示线程池大小
active threads = 5表示当前活跃的线程个数
queued tasks = 1表示在队列等待执行的线程个数,程序中0-5共6个线程,但是目前线程池只有5个,那会有1个线程等待
线程执行完成,但是线程不消失,不需要重新启动新的线程
*/
System.out.println(service);
// 线程池关闭,等待线程全部执行完毕,然后线程池关闭。
service.shutdown();
// 线程池关闭,但是不等待其他执行的线程,立刻关闭线程池
// service.shutdownNow();
// isTerminated判断所有的任务是否都执行完成
System.out.println(service.isTerminated());
// isShutdown判断线程池是否已经关闭,关闭进行中
System.out.println(service.isShutdown());
/*
java.util.concurrent.ThreadPoolExecutor@568db2f2
[Shutting down, pool size = 5, active threads = 5, queued tasks = 1, completed tasks = 0]
Shutting down表示正在关闭
*/
System.out.println(service);
// 主线程休息5秒
TimeUnit.SECONDS.sleep(5);
System.out.println(service.isTerminated());
System.out.println(service.isShutdown());
/*
java.util.concurrent.ThreadPoolExecutor@568db2f2
[Terminated, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 6]
Terminated表示线程结束
completed tasks = 6表示完成任务个数
*/
System.out.println(service);
/*
* 1个线程池维护两个队列:
*
* a.待处理任务队列
* b.已完成任务队列
*/
}
}
thread46 - 线程池
最新推荐文章于 2023-01-16 14:58:06 发布