【发布时间】:2015-08-12 21:02:12
【问题描述】:
我在停止线程时遇到了一点麻烦。我有扫描文件夹中文件的方法。我想要停止此扫描的按钮。按下此按钮后,线程将停止(扫描将停止)并且程序将重置。我试过命令thread.stop();,它有时会起作用(它不再起作用了)。所以我在 * 上阅读了一些主题并尝试了thread.interrupt(); 我的代码然后看起来像这样:
public class myApp extends javax.swing.JFrame {
Thread thread;
int fileCount = 0;
String path = "C:\\Program Files";
public void scanningMethod() {
thread = new Thread(new Runnable() {
public void run() {
while(!thread.interrupted()){
//Recursion method that counting files
dirScan(path);
}
}
});
thread.start();
}
private void stopButtonActionPerformed(java.awt.event.ActionEvent evt) {
//generated button in netBeans
thread.interrupt();
thread.stop();
}
private void dirScan(String dirPath) {
File[] podSoubory = new File(dirPath).listFiles();
for (int i = 0; i < podSoubory.length; i++) {
if (podSoubory[i].isDirectory()) {
String tempPath = podSoubory[i].getAbsolutePath();
System.out.println(tempPath);
if (podSoubory[i].isFile()) {
fileCount++;
}
}
}
}
另一种停止方法仅包含 thread.interrupt();(它有 actionListener 和其他东西)。
可能我做错了什么。你能帮我告诉我点击按钮后如何停止这个正在运行的线程吗? (我知道如何创建可点击按钮)。
【问题讨论】:
-
为了帮助我们充分了解您的问题,请创建并发布您的minimal reproducible example。这不是您的完整程序,这对我们来说可能太多了,但它是一个可编译和可运行的最小示例程序,不需要外部资源(例如文件或图像),或者如果它确实需要我们可以轻松获得的这些资源,我们可以运行和修改这些资源,并为我们展示您的错误。
-
在方法中本地声明线程时,如何中断线程?
-
另请注意,1)我看不到您发布的代码如何获得对感兴趣线程的引用,从而调用
thread.interrupt(),2)如果这是从 Swing GUI 调用的,请考虑使用 SwingWorker 来帮助生成后台线程,因为这可以让您的后台代码与您的 Swing GUI 一起工作。另请注意,SwingWorker 有一个cancel()方法,可能对您的目的有用。并且 3) 我确定您已经阅读过不要使用Thread#stop(),这是危险的代码——我在这里告诉你,你所阅读的内容是真实的——不要调用这个方法。 -
我的程序现在很乱。我的问题是调用 thread.stop(); 后正在运行的线程不会停止;或 thread.interrupt();但是我会在github上添加链接。
-
But I'll add link on github.-- 这不是我们要求或需要的。同样,我们不想看到整个混乱的计划,因为你会要求志愿者付出太多的努力和工作,而我们就是这样。请阅读或重新阅读我第一篇文章中的链接。在此处发布您的相关minimal reproducible example代码和您的问题。
标签: java multithreading swing user-interface