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