ThreadPoolExecutor线程池

本文介绍了一个具体的Java线程池实现案例,通过ThreadPoolExecutor创建线程池,并演示了如何使用自定义任务类(MyTask)来执行多个任务。文章展示了线程池参数设置、任务提交、线程池状态查看及关闭等过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 1 package unit;
 2 
 3 import java.util.concurrent.ArrayBlockingQueue;
 4 import java.util.concurrent.ThreadPoolExecutor;
 5 import java.util.concurrent.TimeUnit;
 6 
 7 public class ThreadPoolExecutor线程池 {
 8     public static void main(String[] args) {
 9         ThreadPoolExecutor executorPool = new ThreadPoolExecutor(5, 15, 2000, TimeUnit.MINUTES, new ArrayBlockingQueue<Runnable>(5));
10         for(int i=0; i<15; i++) {
11             executorPool.execute(new MyTask(i));
12             System.out.println("线程池中线程数目:"+executorPool.getPoolSize()+",队列中等待执行的任务数目:"+
13             executorPool.getQueue().size()+",已执行过的任务数目:"+executorPool.getCompletedTaskCount());
14         }
15         System.out.println("=========================");
16         executorPool.shutdown();
17         executorPool.setKeepAliveTime(2, TimeUnit.MINUTES);
18         
19     }
20 }
21 
22 class MyTask implements Runnable{
23     int theTask = 0;
24     public MyTask() {
25         
26     }
27     public MyTask(int i) {
28         theTask = i;
29         run();
30     }
31     @Override
32     public void run() {
33         System.out.println("当前正在执行第: "+ theTask + " 个线程");
34         /* try {
35             Thread.sleep(1000);
36         } catch (InterruptedException e) {
37             e.printStackTrace();
38         }*/
39         System.out.println("task "+theTask+"执行完毕");
40     }
41 }

 

转载于:https://www.cnblogs.com/redhat0019/p/8034191.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值