线程等待直到文件修改

时间:2017-02-07 15:36:36

标签: java multithreading file

我正在寻找一种方法来休眠线程,直到在Java 1.8中修改文件(如在文件中被触摸和/或更改)。基本上,这个线程必须读取文件的内容,警惕任何更改,但不能吸收核心只是为了读取文件,等待,再次读取,等待等。

理想情况下,一个线程会以与并发阻塞队列使线程进入休眠状态相同的方式阻塞,直到有一些东西要从队列中删除。

有什么想法吗?

1 个答案:

答案 0 :(得分:6)

您可以使用NIO WatchService

  

监视已注册对象的更改和事件的监视服务。例如,文件管理器可以使用监视服务来监视目录以进行更改,以便在创建或删除文件时更新其文件列表的显示。

要使用它,您需要:

// 1 create the watchService
WatchService watchService =    FileSystems.getDefault().newWatchService();

// 2 get a reference to the directory to be watched for changes
String watchedDir = "/mydir";
Path dir = Paths.get(watchedDir);

// 3 register on the events you need to watch
WatchKey watchKey = dir.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

...

// 4 wait for changes, generally inside a loop
watchKey = watchService.take();

方法take在可用时返回一个watch键,否则等待。