我有一個WatchService
拋出了下面的代碼ClosedWatchServiceException
:如何在應用程序關閉時終止WatchService?
final WatchService watchService = FileSystems.getDefault().newWatchService();
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
try {
watchService.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
WatchKey key = null;
while (true) {
key = watchService.take(); //throws ClosedWatchServiceException
//execution
}
我怎樣才能安全地關閉該服務沒有得到例外呢?或者我應該忽略關閉,因爲任何線程在終止應用程序時都會被終止?