如何使用WatchService停止用于观看文件夹的线程?

时间:2013-09-10 15:38:55

标签: 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();
    }
}

2 个答案:

答案 0 :(得分:1)

您可以使用在运行的线程和想要阻止它的线程之间共享的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;
}

答案 1 :(得分:0)

如果你想停止一个线程 - 它的run()方法必须完成并退出。因此,请在run()方法中检查您的条件,以确保它最终完成并退出。