6

我想要实现的是停止线程并等到 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
4

1 回答 1

5

由于 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();

控制台输出:

    Doing some process
    Await
    Done
于 2013-06-08T22:02:48.770 回答