【并发编程】- 线程池执行Callable任务获取返回值

Callable、Future使用

针对线程Thread对象不具有返回值的功能,但是有请求需要线程返回值,所以需要用到Callable和Future来让线程具有返回值的功能。
Callable接口与线程密不可分,但是和Runnable有以下主要的区别是

Callable接口的call()方法可以有返回值,而Runnable接口的run()方法没有返回值。

Callable接口的call()方法可以声明抛出异常,而Runnable接口的run()方法不可以声明抛出异常。
执行完Callable接口中的任务后,返回值是通过Future接口进行获取。

ThreadPoolExecutor使用submit提交Callable的任务

线程执行代码如下:

public class TheCallable implements Callable<String> { private int number; public TheCallable(int number){ super(); this.number=number;
    } @Override public String call() throws Exception {
        Thread.sleep(5000); return "返回值:"+number;
    }
}

运行类代码如下:

@Slf4j public class CallableRun { public static void main(String[] args) {
        TheCallable theCallable = new TheCallable(18);
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 3, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
        Future<String> future = threadPoolExecutor.submit(theCallable); try { log.info("开始时间:{}",System.currentTimeMillis()); log.info("线程 "+future.get()); log.info("结束时间:{}",System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}

运行结果如下:

17:09:57.944 [main] INFO com.ozx.concurrentprogram.executor.controller.CallableRun - 开始时间:165****997940
17:10:02.942 [main] INFO com.ozx.concurrentprogram.executor.controller.CallableRun - 线程 返回值:18
17:10:02.943 [main] INFO com.ozx.concurrentprogram.executor.controller.CallableRun - 结束时间:165****002943

从运行结果看出future调用get()是阻塞的,get()方法具有阻塞特性。
ExecutorService使用submit提交Runnable任务
方法submit()可以传入Callable对象,也可以传入Runnable对象,说明submit()方法支持有返回值和无返回值的功能。
运行类代码如下:

@Slf4j public class RunnableRun { public static void main(String[] args) {
        Runnable runnable = new Runnable() { @Override public void run() {
 SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
                log.info("Runnable 输出的内容:{}",simpleDateFormat.format(new Date()));
            }
        };

        ExecutorService executorService = Executors.newCachedThreadPool();
        Future future = executorService.submit(runnable); try {
            log.info("任务返回值:{},执行isDone方法结果:{}",future.get(),future.isDone());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}

运行结果如下:

17:31:37.704 [pool-1-thread-1] INFO com.ozx.concurrentprogram.executor.controller.RunnableRun - Runnable 输出的内容:17:31:37
17:31:37.715 [main] INFO com.ozx.concurrentprogram.executor.controller.RunnableRun - 任务返回值:null,执行isDone方法结果:true

从运行结果看出submit()方法传入Callable接口则有返回值,但是传入Runnable则无返回值,执行任务的返回值为null,之前验证过方法get()是具有阻塞特性,而isDone()方法是无阻塞特性。


#Java##程序员#
全部评论
不太能看懂
点赞 回复 分享
发布于 2022-08-09 11:23

相关推荐

码砖:求职岗位要突出,一眼就能看到,教育背景放到最后,学校经历没那么重要,项目要重点突出
点赞 评论 收藏
分享
06-15 02:05
已编辑
南昌航空大学 数据分析师
Eason三木:你如果想干技术岗,那几个发公众号合唱比赛的经历就去掉,优秀团员去掉,求职没用。然后CET4这种不是奖项,是技能,放到下面的专业技能里或者单独列一个英语能力。 另外好好改改你的排版,首行缩进完全没有必要,行间距好好调调,别让字和标题背景黏在一起,你下面说能做高质量PPT你得展现出来啊,你这简历排版我用PPT做的都能比你做的好。 然后自我评价,你如果要干数据工程师,抗压能力强最起码得有吧。
简历中的项目经历要怎么写
点赞 评论 收藏
分享
昨天 15:02
门头沟学院 Java
刚打开网申页面就不想填了,还是不要为难自己了
poppinzhan...:多益老行业毒瘤了,碰到徐波这种恶心的烂人,去了也是受罪。
点赞 评论 收藏
分享
评论
点赞
6
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务