根据java doc,Runnable方法void run()不能返回值.我不知道是否有任何解决方法.
其实我有一个调用的方法:
public class Endpoint{
public method_(){
RunnableClass runcls = new RunnableClass();
runcls.run()
}
}
Run Code Online (Sandbox Code Playgroud)
wheren方法run()是:
public class RunnableClass implements Runnable{
public jaxbResponse response;
public void run() {
int id;
id =inputProxy.input(chain);
response = outputProxy.input();
}
}
Run Code Online (Sandbox Code Playgroud)
我想要访问response变量method_()是否可能?
Nar*_*hai 56
使用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);
}
Run Code Online (Sandbox Code Playgroud)
在此示例中,您还需要实现WordLengthCallable类,该类实现Callable接口.
vis*_*aim 14
public void check() {
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> result = executor.submit(new Callable<Integer>() {
public Integer call() throws Exception {
return 10;
}
});
try {
int returnValue = result.get();
} catch (Exception exception) {
//handle exception
}
}
Run Code Online (Sandbox Code Playgroud)
是的,有解决方法。只需使用队列并将您想要返回的值放入其中。并从另一个线程中获取此值。
public class RunnableClass implements Runnable{
private final BlockingQueue<jaxbResponse> queue;
public RunnableClass(BlockingQueue<jaxbResponse> queue) {
this.queue = queue;
}
public void run() {
int id;
id =inputProxy.input(chain);
queue.put(outputProxy.input());
}
}
public class Endpoint{
public method_(){
BlockingQueue<jaxbResponse> queue = new LinkedBlockingQueue<>();
RunnableClass runcls = new RunnableClass(queue);
runcls.run()
jaxbResponse response = queue.take(); // waits until takes value from queue
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72478 次 |
| 最近记录: |