如何从Java的内部Thread Runnable方法获取返回值? [英] How do i get returned value from inner Thread Runnable method in Java?
问题描述
如何使用isFinish()
将Status
与CallMe()
分配为返回值true?
How do i assign Status
with CallMe()
using isFinish()
to have returned value true?
public static boolean isFinish ()
{
boolean Status = false;
new Thread(new Runnable()
{
public void run()
{
/* This shell return true or false
* How do you keep it in Status
*/
CallMe();
}
}).start();
/* How can i get the true or false exactly from CallMe? here */
return Status;
}
public static boolean CallMe()
{
/* some heavy loads ... */
return true;
}
推荐答案
有两种方法. 第一种是使用将来的计算结果,第二种是使用共享变量. 我认为第一种方法比第二种方法干净得多,但是有时您也需要将值推入线程.
There are two ways of doing this. The first is to use a future computation result and the other is to have a shared variable. I think that the first method is much cleaner than the second, but sometimes you need to push values to the thread too.
- 使用
RunnableFuture
.
FutureTask
实现RunnableFuture
.因此,您创建了一个任务,该任务一旦执行便会具有一个值.
FutureTask
implements a RunnableFuture
. So you create that task which, once executed, will have a value.
RunnableFuture f = new FutureTask(new Callable<Boolean>() {
// implement call
});
// start the thread to execute it (you may also use an Executor)
new Thread(f).start();
// get the result
f.get();
- 使用持有人课程
您创建一个包含值的类,并共享对该类的引用.您可以创建自己的类,也可以简单地使用AtomicReference
.
持有人类别,是指具有公开可修改属性的类别.
You create a class holding a value and share a reference to that class. You may create your own class or simply use the AtomicReference
.
By holder class, I mean a class that has a public modifiable attribute.
// create the shared variable
final AtomicBoolean b = new AtomicBoolean();
// create your thread
Thread t = new Thread(new Runnable() {
public void run() {
// you can use b in here
}
});
t.start();
// wait for the thread
t.join();
b.get();
这篇关于如何从Java的内部Thread Runnable方法获取返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!