Wait for Platform.runLater to execute using Latch

What I'm trying to achieve is to stop the thread and wait until doSomeProcess () is called before continuing. But for some strange reason, the whole process got stuck in waiting, and it never ends up in 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 
+4
source share
1 answer

The latch.countDown () statement will never be called since JavaFX Thread is waiting for it to be called; when the JavaFX thread is freed from the latch.wait () method, you will call your runnable.run () method.

Hope this code makes it 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 
+4
source

Source: https://habr.com/ru/post/1484989/


All Articles