java Runnable run()方法返回一个值 [英] java Runnable run() method returning a value

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

问题描述

根据java doc, Runnable 方法 void run()无法返回值。我不知道是否有任何解决方法。

其实我有一个调用的方法:

According to java doc, Runnable method void run() cannot return a value. I do wonder however if there is any workaround of this.

Actually i have a method which calls:

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

wheren方法 run() is:

wheren method run() is:

public class RunnableClass implements Runnable{

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

        }
}

我想访问响应 中的变量方法_()这可能吗?

推荐答案

使用 Callable< V> 而不是使用 Runnable 界面。

示例:

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

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

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