123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354 |
- package J20250731.demo03_threadPool;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.ThreadPoolExecutor;
- /**
- * @author WanJl
- * @version 1.0
- * @title ThreadPoolDemo02
- * @description
- * @create 2025/7/31
- */
- public class ThreadPoolDemo02 {
- public static void main(String[] args) {
- //创建一个线程池,指定核心线程数和最大线程数
- ExecutorService executorService = Executors.newFixedThreadPool(3);
- //把父类对象转换为子类对象
- ThreadPoolExecutor tpe=(ThreadPoolExecutor) executorService;
- System.out.println("线程池的线程数:"+tpe.getPoolSize()); //0
- //如果有任务想要交给线程执行,我们只需要调用executorService的submit方法,把任务传进去
- executorService.submit(()->{
- System.out.println("线程id:"+Thread.currentThread().getId()+",线程名:"+Thread.currentThread().getName()+"在执行了.....");
- });
- //向线程池容器提交一个任务
- executorService.submit(()->{
- System.out.println("线程id:"+Thread.currentThread().getId()+",线程名:"+Thread.currentThread().getName()+"在执行了.....");
- });
- //向线程池容器提交一个任务
- executorService.submit(()->{
- System.out.println("线程id:"+Thread.currentThread().getId()+",线程名:"+Thread.currentThread().getName()+"在执行了.....");
- });
- //向线程池容器提交一个任务
- executorService.submit(()->{
- System.out.println("线程id:"+Thread.currentThread().getId()+",线程名:"+Thread.currentThread().getName()+"在执行了.....");
- });
- //向线程池容器提交一个任务
- executorService.submit(()->{
- System.out.println("线程id:"+Thread.currentThread().getId()+",线程名:"+Thread.currentThread().getName()+"在执行了.....");
- });
- //向线程池容器提交一个任务
- executorService.submit(()->{
- System.out.println("线程id:"+Thread.currentThread().getId()+",线程名:"+Thread.currentThread().getName()+"在执行了.....");
- });
- //再次获取线程数
- System.out.println("线程池的线程数:"+tpe.getPoolSize());
- //关闭线程池
- executorService.shutdown();
- }
- }
|