gpt4 book ai didi

java - 等到使用 Latch 执行 Platform.runLater

转载 作者:搜寻专家 更新时间:2023-11-01 02:48:22 24 4
gpt4 key购买 nike

我想要实现的是暂停线程并等到 doSomeProcess() 被调用后再继续。但是由于一些奇怪的原因,整个过程卡在了 await 中,永远不会进入 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

最佳答案

永远不会调用 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
Done

关于java - 等到使用 Latch 执行 Platform.runLater,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16978557/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com