Java tutorial
//package com.java2s; //License from project: Open Source License import java.util.concurrent.ExecutionException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javafx.application.Platform; public class Main { /** * like Platform.runLater but waits until the thread has finished * based on: http://www.guigarage.com/2013/01/invokeandwait-for-javafx/ * @param r the runnable to run in a JavaFX thread */ public static void platformRunAndWait(final Runnable r) throws Throwable { if (Platform.isFxApplicationThread()) { try { r.run(); } catch (Exception e) { throw new ExecutionException(e); } } else { final Lock lock = new ReentrantLock(); final Condition condition = lock.newCondition(); final boolean[] done = { false }; // to get around the requirement for final final Throwable[] ex = { null }; lock.lock(); try { Platform.runLater(() -> { lock.lock(); try { r.run(); } catch (Throwable e) { ex[0] = e; } finally { try { done[0] = true; condition.signal(); } finally { lock.unlock(); } } }); while (!done[0]) condition.await(); if (ex[0] != null) { // re-throw exception from the runLater thread throw ex[0]; } } finally { lock.unlock(); } } } public static void runLater(final Runnable r) { Thread t = new Thread(r, "ThreadUtils.runLater-Thread"); t.setDaemon(true); t.start(); } }