简体   繁体   English

等到使用Latch执行Platform.runLater

[英]Wait until Platform.runLater is executed using Latch

What I am trying to achieve is to halt the thread and wait until doSomeProcess() is called before proceeding. 我想要实现的是暂停线程并等待直到继续之前调用doSomeProcess()。 But for some strange reason, the whole process got stuck at await and it never get into the Runnable.run. 但由于一些奇怪的原因,整个过程陷入等待,它永远不会进入Runnable.run。

Code snippet : 代码段:

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");

Console output : 控制台输出:

Await

The latch.countDown() statement will never be called since the JavaFX Thread is waiting for it to be called; 由于JavaFX线程正在等待调用它,因此永远不会调用latch.countDown()语句; when the JavaFX thread get released from the latch.wait() your runnable.run() method will be called. 当从latch.wait()释放JavaFX线程时,将调用runnable.run()方法。

I hope this code make the thing clearer 我希望这段代码能让事情更加清晰

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

Console output: 控制台输出:

    Doing some process
    Await
    Done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM