如何从Java中的内部Thread Runnable方法获取返回值?

时间:2011-10-10 14:40:30

标签: java multithreading

如何使用Status CallMe()分配isFinish()以使返回值为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;
}

3 个答案:

答案 0 :(得分:27)

有两种方法可以做到这一点。 第一种是使用未来的计算结果,另一种是使用共享变量。 我认为第一种方法比第二种方法更清晰,但有时你也需要将值推送到线程。

  • 使用RunnableFuture

FutureTask实现RunnableFuture。所以你创建了一个任务,一旦执行,就会有一个值。

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。 持有者类,我的意思是一个具有公共可修改属性的类。

// 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();

答案 1 :(得分:3)

您重写代码以使用Callable<Boolean>并在启动Future时获得Runnable

Futures允许启动线程正确检查值是否准备好并异步读取它。您可以手动编写代码,但由于Future现在是标准JVM库的一部分,为什么(编程类之外)?

答案 2 :(得分:1)

使用原始线程,您可以使用命名类型实现Runnable,并将值存储在其中。

class MyRunnable implements Runnable {
   boolean status;

   public void run() {
      ...
   }
}

但是,如果您正在使用其他线程,则必须以某种方式进行同步。

使用java.util.concurrent层次结构提供的更高级别的工具会更容易。您可以向执行者提交一个Callable,并获得一个Future。您可以询问未来是否已完成,并获得结果。有Oracle tutorial here