简体   繁体   中英

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. But for some strange reason, the whole process got stuck at await and it never get into the 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; when the JavaFX thread get released from the latch.wait() your runnable.run() method will be called.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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