如何杀死Watch Service线程

时间:2016-12-15 21:59:10

标签: java watchservice

我需要根据来自我的UI的请求观看HotFolder 我在我的用户界面上有启动和停止按钮,当我点击开始我的代码应该看文件夹并点击停止它应该停止观看它。我正在使用观看服务来观看HotFolder,我正在从我的控制器传递旗帜来观看服务以开始和停止观看文件夹。请建议我如何停止观看文件夹?

以下是代码段:

DatabaseError

HotFolder.java:

@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;
}

1 个答案:

答案 0 :(得分:0)

肯定有些事你没有提及,因为我看到的注释让我觉得你正在使用某种基于REST的库。

无论如何,你的代码永远不会起作用。那是因为你基本上把回答你问题的线程转变为观察线程,这永远不会完成你的工作。我建议使用Singleto Pattern,像这样编写您的HotFolder类:

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)