我试图阻止WatchService工作的线程。但怎么做呢?我的WatchService在那里的文件夹中等待新更新:
key = watchService.take(); 我在那里开始我的线:
private void startButtonActionPerformed(ActionEvent e) {
stateLabel.setText("monitoring...");
try {
watchService = FileSystems.getDefault().newWatchService();
} catch (IOException e1) {
e1.printStackTrace();
}
watchThread = new WatchThread(watchService, key);
Thread t = new Thread(watchThread);
t.start();
}我试图停止:
private void stopButtonActionPerformed(ActionEvent e) {
try {
if (watchService!=null) {
key.cancel();
watchService.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}当我尝试执行stop时,我会得到键中的NullPointerException。当我用watchService关闭watchService.close()时,我得到了另一个例外:ClosedWatchServiceException。
如何毫无例外地关闭WatchService?对不起我的英语不好..。
发布于 2013-09-06 19:12:39
您正在获得的异常正在发生,因为您没有控制UI事件。
当您尝试使用已调用其ClosedWatchServiceException方法的WatchService时,就会发生close()。因此,您可能在调用watchService.take()之后调用close()或其他一些WatchService方法。在关闭take()并立即抛出Exception之后,可能会发生WatchService方法解除阻塞的情况。
您得到了一个带有NullPointerException的key,因为在初始化它之前,您正在尝试在实例上调用cancel()。我猜在你班上的某个地方
private WatchKey key;默认情况下,实例引用类型变量初始化为null。如果你的死刑从来没有带过你
key = watchService.take(); 那么key仍将是null。
https://stackoverflow.com/questions/18664539
复制相似问题