我想停止使用 jToggleButton 以下列方式生成的线程。线程用于查看文件夹中的文件。我尝试了很多,搜索了很多,但没有成功。任何机构都可以提供帮助并提出任何解决方案来停止生成类似的线程。即使在按下 jToggleButton 后,线程在 Netbeans 调试中仍显示为活动状态。我已经尝试过用于停止的不稳定条件,仅供参考:我有一个用于启动和停止线程的 jToggle 按钮。
代码是由Netbeans生成的,所以有一些额外的代码,但你可能只关注jToggleActionListener里面的代码和另一个类的代码:谢谢你的帮助。
package threadnames;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class NewJFrame extends javax.swing.JFrame {
public NewJFrame() {
initComponents();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jToggleButton1 = new javax.swing.JToggleButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jToggleButton1.setText("Stop");
jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jToggleButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(84, 84, 84)
.addComponent(jToggleButton1)
.addContainerGap(142, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jToggleButton1)
.addContainerGap(28, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {
ExecutorService exec = Executors.newCachedThreadPool();
if (this.jToggleButton1.isSelected()) {
try {
// TODO add your handling code here:
Path home = Paths.get(System.getProperty("user.dir"));
WatchService watcher;
watcher = home.getFileSystem().newWatchService();
home.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
Runnable task = new FileWatch(watcher);
exec.submit(task);
boolean terminated;
terminated = exec.awaitTermination(1, TimeUnit.SECONDS);
if (terminated) {
System.out.println("All tasks completed.");
} else {
System.out.println("Some tasks are still running.");
}
} catch (IOException | InterruptedException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
exec.shutdownNow();
}
}
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class
.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
public javax.swing.JToggleButton jToggleButton1;
// End of variables declaration
}
这是 run() 的另一个类:
package threadnames;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.nio.file.Watchable;
final class FileWatch implements Runnable {
private final WatchService watcher;
FileWatch(WatchService watcher) {
this.watcher = watcher;
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
break;
}
Watchable dir = key.watchable();
System.out.println(dir);
for (WatchEvent<?> evt : key.pollEvents()) {
System.out.println(" " + evt.context());
}
}
}
}