两种情况:
1:不阻塞当前线程
2:当runlater返回之后当前线程才继续运行
在 JavaFx 中,如果在非Fx线程要执行Fx线程相关的任务,必须在 Platform.runlater 中执行,
而 runlater 中代码将不会阻塞当前线程,所以当需要 runlater 中代码执行返回值,再顺序执行后续代码时,需要采用以下方法:
// 定义一个FutureTask,然后 Plateform.runLater() 这个futuretask
final FutureTask<String> query = new FutureTask<String>(new Callable<String>() {
@Override
public String call() throws Exception {
// 新建一个窗口(方法中将创建stage)
VcodeController vc = new VcodeController();
return vc.show(url4vcode);
}
});
Platform.runLater(query); // 重点
String vcode = query.get(); // 这样就能获取返回值
System.out.println(vcode);
另外一种做法,利用 CountDownLatch
/**
* Runs the specified {@link Runnable} on the
* JavaFX application thread and waits for completion.
*
* @param action the {@link Runnable} to run
* @throws NullPointerException if {@code action} is {@code null}
*/
public static void runAndWait(Runnable action) {
if (action == null)
throw new NullPointerException("action");
// run synchronously on JavaFX thread
if (Platform.isFxApplicationThread()) {
action.run();
return;
}
// queue on JavaFX thread and wait for completion
final CountDownLatch doneLatch = new CountDownLatch(1);
Platform.runLater(() -> {
try {
action.run();
} finally {
doneLatch.countDown();
}
});
try {
doneLatch.await();
} catch (InterruptedException e) {
// ignore exception
}
}
————————————————
版权声明:本文为CSDN博主「tstudy」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u010061897/article/details/69358246
来源:oschina
链接:https://my.oschina.net/u/2963604/blog/3161045