0
我有一个要求,根据来自我的UI的请求观看HotFolder 我有我的用户界面上的启动和停止按钮,当我点击开始我的代码应该观看文件夹并点击停止它应该停止观看它。我正在使用手表服务来观看HotFolder,我正在从我的控制器传递标志以观看服务以开始和停止观看文件夹。请建议我如何停止观看文件夹?如何杀死观看服务线程
以下是代码片段:
@RequestMapping(value = "/start", method = RequestMethod.GET)
public ModelAndView hotFolder()
{
ModelAndView model = new ModelAndView();
model.setViewName("welcomePage");
HotFolder h = new HotFolder();
h.hotfolderTesting(true);
return model;
}
@RequestMapping(value = "/stop", method = RequestMethod.POST)
public ModelAndView hotFolderStop()
{
ModelAndView model = new ModelAndView();
model.setViewName("welcomePage");
HotFolder h = new HotFolder();
h.hotfolderTesting(false);
return model;
}
HotFolder.java:
public void hotfolderTesting(boolean flag)
{
try (WatchService service = FileSystems.getDefault().newWatchService()) {
Map<WatchKey, Path> keyMap = new HashMap<>();
Path path = Paths.get("E:\\TestingWatch");
keyMap.put(path.register(service, StandardWatchEventKinds.ENTRY_CREATE), path);
WatchKey watchKey;
if (flag) {
while (true) {
watchKey = service.take();
for (WatchEvent<?> event : watchKey.pollEvents()) {
if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("Created: " + event.context());
} else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println("Deleted: " + event.context());
} else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
System.out.println("Modified :" + event.context());
}
}
if (!watchKey.reset()) {
break;
}
}
}
} catch (Exception ignored) {
}
}
我在公共无效setRunning(布尔运行)获得java.lang.IllegalThreadStateException { \t \t this.running = running; \t \t if(running){ \t \t \t this.start(); \t \t} \t} – user7076183
好吧,似乎一个线程不能启动超过一个。我将更改代码以使用runnables。 – bracco23
仍然没有运气:(一些时间线程成为空..有些时候没有..即使当我点击停止按钮(这是调用HotFolder.getInstance()。setRunning(false)方法)仍然看文件夹..(仍然记录在文件夹中创建的新文件) – user7076183