| 12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- package course;
- import java.util.concurrent.*;
- /**
- * @author WanJl
- * @version 1.0
- * @title ThreadPoolDemo
- * @description
- * @create 2026/8/11
- */
- public class ThreadPoolDemo {
- public static void main(String[] args) {
- ThreadPoolExecutor pool=
- new ThreadPoolExecutor(2,4,60, TimeUnit.SECONDS,new ArrayBlockingQueue<>(2), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
- for (int i = 1; i <=8; i++) {
- int taskId=i;
- try{
- pool.execute(()->{
- String name = Thread.currentThread().getName();
- System.out.println(name+"执行任务"+taskId);
- try {
- Thread.sleep(2000); //模拟任务耗时,占住线程
- } catch (InterruptedException e) {
- throw new RuntimeException(e);
- }
- });
- }catch (RejectedExecutionException e){
- System.out.println("任务"+ taskId+"被拒绝"+e.getMessage());
- }
- }
- //观察线程池的状态:活动线程数、队列的大小
- System.out.println("活动线程数:"+pool.getActiveCount());
- System.out.println("队列中任务数:"+pool.getQueue().size());
- pool.shutdown(); //关闭线程池
- }
- }
|