【问题标题】:Wait until Platform.runLater is executed using Latch等到 Platform.runLater 使用 Latch 执行
【发布时间】:2013-06-03 10:24:09
【问题描述】:

我想要实现的是停止线程并等到 doSomeProcess() 被调用后再继续。但是由于某种奇怪的原因,整个过程卡在了 await 中,它永远不会进入 Runnable.run。

代码sn-p:

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

【问题讨论】:

  • 您是否尝试过在doSomeProcess() 之前进行输出?我猜这个函数没有返回,仅此而已。
  • 我更新了我的代码 sn-p。它甚至无法到达 run 方法。
  • 是否有东西阻塞了 GUI 线程?还是您在 GUI 线程上执行整个剪辑?
  • 我不确定。我怎么知道它是否在 GUI-Thread 上执行?但是上面的 sn-p 是我仅有的一段代码。仅此而已。
  • 我想这就是问题所在。如果您应该异步执行doSomeProcess,请在不同的线程上执行。我对JavaFX不太了解,也许有某种“AsyncTask”类?

标签: java javafx


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 2012-08-12
    • 2018-04-05
    相关资源
    最近更新 更多