我试图实现的是暂停线程并等待,直到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发布于 2013-06-09 06:02:49
latch.countDown()语句永远不会被调用,因为JavaFX线程正在等待它被调用;当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
Donehttps://stackoverflow.com/questions/16978557
复制相似问题