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

2022-07-06 11:49:48

我的个人网站:等不见天亮等时光

  • 多线程下获取执行方法的返回值,实现线程的几种方法,大家都是比较清楚的,而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;
    }
  • 作者:等不见天亮等时光i
  • 原文链接:https://blog.csdn.net/suodod/article/details/105263119
    更新时间:2022-07-06 11:49:48