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 {//方式1for (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();}});}//方式2for (Taskinfo taskObj: taskinfoLst) {threadPool.execute(new Runnable() {@Overridepublic void run() {//执行任务方法(taskObj);context.getTaskManager().executeMothod(taskObj);}});}} catch (Exception e2) {// TODO: handle exception}finally {threadPool.shutdown();}}}