java - 如何使用 WatchService 停止用于监视文件夹的线程?

标签 java multithreading concurrency

我想停止按以下方式生成的线程。这些线程用于监视文件夹中的文件。我尝试了很多,也搜索了很多,但没有成功。

任何机构都可以提供帮助并提出任何解决方案来停止生成如下线程:

public class HelloRunnable implements Runnable {
    public void run() {
         WatchService for files in folders which starts and runs here
         while (someCondition) {
               create a thread for copying some file which exits when run() finishes 
               created in another class which implements Runnable class
         }
    }

    public static void main(String args[]) {
       for(int i = 0;i< 5; i ++)
        new Thread(new HelloRunnable()).start();
    }
}

最佳答案

您可以使用在正在运行的线程和想要停止它的线程之间共享的boolean someCondition变量。但是,此变量需要是 volatile ,以确保其值在线程之间更新。

另一个想法是测试线程中断标志:

// thread that is spinning doing some job like watching a file
while (!Thread.currentThread().isInterrupted()) {
   ...
}

然后你可以从另一个线程调用中断来停止它的运行:

Thread thread = new Thread(...);
thread.start();
...
// tell the thread running in the background to stop
thread.interrupt();

像往常一样,您需要小心捕获InterruptedException。像下面这样的东西总是一个好主意:

try {
    ...
} catch (InterruptedException ie) {
    // re-interrupt the thread now that we've caught InterruptedException
    Thread.currentThread().interrupt();
    // probably quit the thread
    return;
}

关于java - 如何使用 WatchService 停止用于监视文件夹的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18723257/

相关文章:

java - KeyListener 在 Java 中不起作用

c - 我如何在 win32 平台上用 C 实现时间驱动的任务?

c++ - 不使用线程的c++ dll无限循环

python - 我不明白为什么多线程代码无法获取 lineedit.text()

ios - dispatch_sync(dispatch_get_global_queue(xxx), task) 是同步还是异步

java - 检索struts2中选择框的值

java - 哪个Java阻塞队列对于单生产者单消费者场景最有效

java - 为什么在我的 BST 中序遍历中显示的是指针而不是字符串?

java - 具有同步支持的自动增量数

JavaFX8 后台线程仍然干扰 GUI