Runnable
的run
方法有返回类型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/