线程池处理Callable任务
线程池如何处理Callable任务
线程池如何处理Callable任务,并得到任务执行完后返回的结果。
使用ExecutorService的方法:
Future<T> submit(Callable<T> command)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | package com.itheima.d8_threadpool; import java.util.concurrent.Callable; /** 1、定义一个任务类 实现Callable接口 应该申明线程任务执行完毕后的结果的数据类型 */ public class MyCallable implements Callable<String>{ private int n; public MyCallable( int n) { this .n = n; } /** 2、重写call方法(任务方法) */ @Override public String call() throws Exception { int sum = 0 ; for ( int i = 1 ; i <= n ; i++) { sum += i; } return Thread.currentThread().getName() + "执行 1-" + n+ "的和,结果是:" + sum; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | package com.itheima.d8_threadpool; import java.util.concurrent.*; /** 目标:自定义一个线程池对象,并测试其特性。 */ public class ThreadPoolDemo2 { public static void main(String[] args) throws Exception { // 1、创建线程池对象 /** public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) */ ExecutorService pool = new ThreadPoolExecutor( 3 , 5 , 6 , TimeUnit.SECONDS, new ArrayBlockingQueue<>( 5 ) , Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy() ); // 2、给任务线程池处理。 Future<String> f1 = pool.submit( new MyCallable( 100 )); Future<String> f2 = pool.submit( new MyCallable( 200 )); Future<String> f3 = pool.submit( new MyCallable( 300 )); Future<String> f4 = pool.submit( new MyCallable( 400 )); Future<String> f5 = pool.submit( new MyCallable( 500 )); // String rs = f1.get(); // System.out.println(rs); System.out.println(f1.get()); System.out.println(f2.get()); System.out.println(f3.get()); System.out.println(f4.get()); System.out.println(f5.get()); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY