gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 20:59:23 25 4
gpt4 key购买 nike

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

最佳答案

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

  • 使用 RunnableFuture

FutureTask 实现了一个 RunnableFuture。因此,您创建了该任务,该任务一旦执行就会产生值(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();
  • 使用 holder 类

您创建一个包含一个值的类并共享对该​​类的引用。您可以创建自己的类或简单地使用 AtomicReference。持有者类是指具有公共(public)可修改属性的类。

// 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 - 我如何从 Java 中的内部 Thread Runnable 方法获取返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7714432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com