java创建线程池去实现某个任务(多线程)

1.ThreadPoolExecutor创建线程池的完整Java示例代码,包含核心参数配置和基本使用方法:
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
corePoolSize, //核心线程数(corePoolSize)=15:线程池保持的最小线程数
maxPoolSize, //最大线程数(maximumPoolSize)=30:线程池允许创建的最大线程数
keepAliveTime, //空闲线程存活时间(keepAliveTime)=0毫秒:非核心线程空闲时立即回收
TimeUnit.SECONDS, //
workQueue, //任务队列(workQueue)=容量512的LinkedBlockingQueue:用于存放待执行任务
new ThreadPoolExecutor.AbortPolicy() // 拒绝策略
);
2.代码实例

public static void main(String[] args) 
    {
		ExecutorService threadPool = new ThreadPoolExecutor(
                15, //线程池保持的最小线程数
                30, //线程池允许创建的最大线程数
	            0L, //空闲线程存活时间(keepAliveTime)=0毫秒:非核心线程空闲时立即回收
                TimeUnit.MILLISECONDS,
	            new LinkedBlockingQueue<>(512), //任务队列(workQueue)=容量512的LinkedBlockingQueue:用于存放待执行任务
                new ThreadPoolExecutor.AbortPolicy());//拒绝策略
		try 
		{
            //方式1
		    for (int i = 0; i < 20; i++) {
	            final int taskId = i;
	            threadPool.execute(() -> {
	                System.out.println("执行任务: " + taskId + " 线程: " + Thread.currentThread().getName());
	                try {
	                    Thread.sleep(1000);
	                } catch (InterruptedException e) {
	                    e.printStackTrace();
	                }
	            });
	            }
            //方式2
            for (Taskinfo taskObj: taskinfoLst) {
					threadPool.execute(new Runnable() {
						@Override
						public void run() {
							//执行任务方法(taskObj);
                            context.getTaskManager().executeMothod(taskObj);
						}
					});
		   }
		} catch (Exception e2) {
			// TODO: handle exception
		}finally 
		{
			threadPool.shutdown();
		}
	}

}
posted on 2025-09-23 10:47  willian知识库  阅读(10)  评论(0)    收藏  举报