我该如何分配Status
with CallMe()
using 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;
}
有两种方法可以做到这一点。
第一个是使用未来的计算结果,另一个是共享变量。
我认为第一种方法比第二种方法干净得多,但有时您也需要将值推送到线程。
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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)