0%

使用CountLatch实现异步等待

10.async-wait-with-latch

利用CountLatch异步等待

摘自JavaFx源码

com.sun.javafx.application.LauncherImpl#launchApplication(java.lang.Class<? extends javafx.application.Application>, java.lang.Class<? extends javafx.application.Preloader>, java.lang.String[])

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// 接收异常
private static volatile RuntimeException launchException = null;


final CountDownLatch launchLatch = new CountDownLatch(1);
Thread launcherThread = new Thread(() -> {
try {
launchApplication1(appClass, preloaderClass, args);
} catch (RuntimeException rte) {
launchException = rte;
} catch (Exception ex) {
launchException =
new RuntimeException("Application launch exception", ex);
} catch (Error err) {
launchException =
new RuntimeException("Application launch error", err);
} finally {
// countDown
launchLatch.countDown();
}
});
launcherThread.setName("JavaFX-Launcher");
launcherThread.start();
// 异步线程启动

// Wait for FX launcher thread to finish before returning to user
try {
launchLatch.await();
} catch (InterruptedException ex) {
throw new RuntimeException("Unexpected exception: ", ex);
}

if (launchException != null) {
throw launchException;
}