我想要实现的是停止线程并等待直到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");
Run Code Online (Sandbox Code Playgroud)
控制台输出:
Await
Run Code Online (Sandbox Code Playgroud)
由于 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();
Run Code Online (Sandbox Code Playgroud)
控制台输出:
Doing some process
Await
Done
Run Code Online (Sandbox Code Playgroud)