我想停止按以下方式生成的线程。这些线程用于监视文件夹中的文件。我尝试了很多,也搜索了很多,但没有成功。
任何机构都可以提供帮助并提出任何解决方案来停止生成如下线程:
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/