這算是CountDownLatch的一個典型使用場景。java
kafka.Kafka對象的main方法中與此有關的代碼爲ide
// attach shutdown handler to catch control-c Runtime.getRuntime().addShutdownHook(new Thread() { override def run() = { kafkaServerStartble.shutdown } }) kafkaServerStartble.startup kafkaServerStartble.awaitShutdown System.exit(0)
首先,註冊一個shutdownHook,在control-c等令虛擬機中止命令後,虛擬機會啓動被註冊的hook對應的線程,在這裏,server的shutdown方法將被調用。線程
而後,啓動server。在server的startup方法中,會初始化一個CountDownLatch爲1。這時,server的各個子服務開始運行。server
而後,調用server的awaitShutdown方法,使得main線程阻塞。對象
def awaitShutdown(): Unit = shutdownLatch.await()
這個方法就是簡單地調用CountDownLatch的await方法。而以前提到的,server的shutdown方法就是在中止server的各個服務後,調用CountDownLatch的countDown方法,這時,阻塞在await的main線程就會醒來,從而調用System.exit。blog
綜上,control-c 使shutDown在shutDownHook的線程中被調用,從而使CountDownLatch減1,使得以前阻塞在同一個CountDownLatch的main線程繼續,從而調用 System.exit推出JVM。get