如何从Java中的内部Thread Runnable方法获取返回值?
如何使用isFinish()
为CallMe()
分配Status
以使返回值为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; }
有两种方法可以做到这一点。 第一种是使用未来的计算结果,另一种是使用共享变量。 我认为第一种方法比第二种方法更清晰,但有时你需要将值推送到线程中。
- 使用
RunnableFuture
。
FutureTask
实现了RunnableFuture
。 所以你创建了一个任务,一旦执行,就会有一个值。
RunnableFuture f = new FutureTask(new Callable() { // implement call }); // start the thread to execute it (you may also use an Executor) new Thread(f).start(); // get the result f.get();
- 使用持有人类
您创建一个包含值的类并共享对该类的引用。 您可以创建自己的类或只使用AtomicReference
。 持有者类,我的意思是一个具有公共可修改属性的类。
// 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();
您重写代码以使用Callable
并在启动Runnable
时获取Future
。
Futures允许启动线程正确检查值是否准备好并异步读取它。 您可以手动编写代码,但由于Future
现在是标准JVM库的一部分,为什么(编程类之外)?
使用原始线程,您可以使用命名类型实现Runnable,并将值存储在其中。
class MyRunnable implements Runnable { boolean status; public void run() { ... } }
但是,如果您正在使用另一个线程,则必须以某种方式进行同步。
使用java.util.concurrent层次结构提供的更高级别的工具会更容易。 您可以向执行者提交一个Callable,并获得一个Future。 您可以询问未来是否已完成,并获得结果。 这里有一个Oracle教程 。