我需要根据我的UI的要求观看热门人我的UI上有启动和停止按钮,当我单击"启动"代码时,我的代码应观看文件夹并单击"停止",它应该停止观看它。我正在使用手表服务来观看热门人,我正在从控制器上传递标志,以观看服务,以开始和停止观看文件夹。请建议我如何停止观看文件夹?
这是代码段:
@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) {
}
}
肯定有您没有提及的东西,因为我看到注释让我认为您正在使用某种基于休息的库。
无论如何,您的代码永远无法正常工作。那是因为您基本上是在将回答问题的线程转换为观看线程,而这永远不会完成您的工作。我建议一个单身图案,以这样的方式写下您的hotfolter类:
public class HotFolder implements Runnable{
private static HotFolder instance = null;
public static HotFolder getInstance(){
if(instance == null)
instance = new HotFolder();
return instance;
}
private boolean running = false;
private Thread t = null
private HotFolder(){
}
public setRunning(boolean running){
this.running = running;
if(running && t == null){
t = new Thread(this);
t.start()
}else if(!running && t!= null){
t = null;
}
}
public boolean getRunning(){
return running;
}
public void run(){
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;
watchKey = service.take();
do{
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());
}
}
}while(running && watchKey.reset());
} catch (Exception ignored) {
}
}
}
然后您称其为
//to activate
HotFolder.getInstance().setRunning(true)
//to stop it
HotFolder.getInstance().setRunning(false)