java多线程下获取方法返回值

我的个人网站:等不见天亮等时光
  • 多线程下获取执行方法的返回值,实现线程的几种方法,大家都是比较清楚的,而runable接口是void类型,无返回值,想通过runable来获取返回值,只能再起一个方法调度进行异步回调,而多线程实现的另一个方法Callable方法是有一个任意值对象的返回的;
    在这里插入图片描述
  • 如下
  • 实现callable方法实现call方法,返回object对象
  • 在call方法中调用要被执行的逻辑方法
    在这里插入图片描述
  • 开启多线程
    在这里插入图片描述在这里插入图片描述
  • 线程的执行方法execute和submit,execute方法入参需要一个runable对象
    在这里插入图片描述
  • submit方法需要的是一个callable对象
    在这里插入图片描述
  • 返回值是一个Future对象,在源码中我们可以看到这样一段注释:返回值根据Future的get方法进行获取的
The result type returned by this Future's {@code get} method
  • 还有这样一个方法,根据此方法可以判断出任务是否完成,完成返回为true
/**
     * Returns {@code true} if this task completed.
     *
     * Completion may be due to normal termination, an exception, or
     * cancellation -- in all of these cases, this method will return
     * {@code true}.
     *
     * @return {@code true} if this task completed
     */
    boolean isDone();
  • 如下
 public String outBreakStatisTask() {
        String s = "";
        if (ExcuterService.excuterService.isShutdown()) {
            //开启多线程
            Future submit = ExcuterService.excuterService.submit(new OutstaticService());
            if (submit.isDone()) {
                try {
                    s = submit.get().toString();
                } catch (Exception e) {
                    log.error("错误:[{}]",e.getMessage());
                }
            }
        }
        return s;
    }
  • 以上!!感谢点赞
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值