java - 从 Runnable 返回一个值

标签 java runnable

Runnablerun方法有返回类型void,不能返回值。但是我想知道是否有任何解决方法。

我有这样的方法:

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();
    }
}

我想访问 method 中的 response 变量。这可能吗?

最佳答案

使用 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界面。

关于java - 从 Runnable 返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13684468/

相关文章:

java - Runnable 中的无限循环消失了?

Android忽略runOnUiThread中语言文件中的字符串

java - 在android中创建vcf文件时出错

java - ScheduledExecutorService - 忽略已经运行的可运行对象

android - Handler Runnable 甚至在 Activity 退出后运行

java - 可运行参数

java - 按下 ENTER 键后 JtextArea 光标位置

java - CSV 保留 CRLF 同时替换 LF

java - Katalon Debian headless 浏览器

java - 不同操作系统中的不同结果