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

12 java multithreading

我如何分配StatusCallMe()使用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;
}
Run Code Online (Sandbox Code Playgroud)

Kru*_*Kru 26

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

  • 用一个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();
Run Code Online (Sandbox Code Playgroud)
  • 使用持有者类

您创建一个包含值的类并共享对该​​类的引用.您可以创建自己的类或只使用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();
Run Code Online (Sandbox Code Playgroud)