返回值的Java Runnable run()方法

Grzzzzzzzzzzzzzzz:

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

其实我有一个方法,它调用:

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

wheren方法run()是:

public class RunnableClass implements Runnable{

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

        }
}

我想访问response变量method_()是否可行?

Narendra Pathai:

使用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接口。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章