我想要实现的是暂停线程并等待直到调用doSomeProcess()才继续。但由于一些奇怪的原因,整个过程陷入等待,它永远不会进入Runnable.run。
代码段:
final CountDownLatch latch = new CountDownLatch(1);
Platform.runLater(new Runnable() {
@Override public void run() {
System.out.println("Doing some process");
doSomeProcess();
latch.countDown();
}
});
System.out.println("Await");
latch.await();
System.out.println("Done");
控制台输出:
Await
答案 0 :(得分:4)
由于JavaFX线程正在等待调用它,因此永远不会调用latch.countDown()语句;当从latch.wait()释放JavaFX线程时,将调用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