java 多线程(ThreadPoolExecutor (补充))
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; public class App { private ThreadPoolExecutor threadpool; public App(){ /*参数依次是: corePoolSize - 池中所保存的线程数,包括空闲线程。 maximumPoolSize - 池中允许的最大线程数。 keepAliveTime - 当线程数大于核心时,此为终止前多余的空闲线程等待新任务的最长时间。 unit - keepAliveTime 参数的时间单位。 workQueue - 执行前用于保持任务的队列。此队列仅由保持 execute 方法提交的 Runnable 任务。 handler - 由于超出线程范围和队列容量而使执行被阻塞时所使用的处理程序。*/ //规则: //1. 池中线程数量小于corePoolSize, 即使存在空闲线程,也启动新线程处理新任务; //2. 池中显成熟等于corePoolSize,则添加至workQueue; //3. 若此时连workQueue也满,但线程数小于maximumPoolSize, 则添加新线程处理新任务; //4. 若超过maximumPoolSize 则调用handler 处理 // DiscardOldestPolicy -> 放弃最末的处理请求 threadpool = new ThreadPoolExecutor(2,3, 10, TimeUnit. SECONDS, new ArrayBlockingQueue(2), new ThreadPoolExecutor.DiscardOldestPolicy()); } public void subMit(final int value){ threadpool.execute(new Runnable(){ @Override public void run() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.print(value + "_hello\r\n"); } }); } public void shutdown() { threadpool.shutdown(); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub App app = new App(); for(int i = 0; i < 5;i++){ app.subMit(i); } //输出:当threadpool = new ThreadPoolExecutor(2,3, 10, TimeUnit. //SECONDS, new ArrayBlockingQueue(1), //3_hello //1_hello //0_hello //4_hello //输出:当threadpool = new ThreadPoolExecutor(2,3, 10, TimeUnit. //SECONDS, new ArrayBlockingQueue(2), //0_hello //1_hello //4_hello //3_hello //2_hello app.shutdown(); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)