由于 JavaFX 线程正在等待它被调用,因此将永远不会调用 latch.countDown() 语句;当 JavaFX 线程从 latch.wait() 中释放时,您的 runnable.run() 方法将被调用。
我希望这段代码能让事情更清楚
final CountDownLatch latch = new CountDownLatch(1);
// asynchronous thread doing the process
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Doing some process");
doSomeProcess(); // I tested with a 5 seconds sleep
latch.countDown();
}
}).start();
// asynchronous thread waiting for the process to finish
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Await");
try {
latch.await();
} catch (InterruptedException ex) {
Logger.getLogger(Motores.class.getName()).log(Level.SEVERE, null, ex);
}
// queuing the done notification into the javafx thread
Platform.runLater(new Runnable() {
@Override
public void run() {
System.out.println("Done");
}
});
}
}).start();
控制台输出:
Doing some process
Await
Done