从Runnable返回值 [英] Returning a value from Runnable

查看:94
本文介绍了从Runnable返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Runnable 的 run 方法的返回类型为 void ,并且无法返回值.但是我不知道是否有任何解决方法.

The run method of Runnable has return type void and cannot return a value. I wonder however if there is any workaround of this.

我有一个这样的方法:

public class Endpoint {
    public method() {
       Runnable runcls = new RunnableClass();
       runcls.run()
    }
}

run 方法是这样的:

public class RunnableClass implements Runnable {
    
    public JaxbResponse response;

    public void run() {
        int id = inputProxy.input(chain);
        response = outputProxy.input();
    }
}

我想访问方法中的 response 变量.这可能吗?

I want to have access to response variable in method. Is this possible?

推荐答案

使用 Callable< V> 而不是使用 Runnable 接口.

示例:

public static void main(String args[]) throws Exception {
    ExecutorService pool = Executors.newFixedThreadPool(3);
    Set<Future<Integer>> set = new HashSet<>();

    for (String word : args) {
      Callable<Integer> callable = new WordLengthCallable(word);
      Future<Integer> future = pool.submit(callable);
      set.add(future);
    }

    int sum = 0;
    for (Future<Integer> future : set) {
      sum += future.get();
    }

    System.out.printf("The sum of lengths is %s%n", sum);
    System.exit(sum);
}

在此示例中,您还将需要实现 WordLengthCallable 类,该类实现了 Callable 接口.

In this example, you will also need to implement the class WordLengthCallable, which implements the Callable interface.

这篇关于从Runnable返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆