gpt4 book ai didi

java - 使用连续线程时 JVM 无缘无故关闭

转载 作者:太空宇宙 更新时间:2023-11-04 12:21:41 25 4
gpt4 key购买 nike

我的程序遇到问题。我正在尝试按结尾对下载的文件进行排序。到目前为止,我已经获得了用于观察给定文件路径并在 HashSet 中列出这些文件的结构。我现在的问题是,程序继续运行几秒钟,然后以退出代码 0 结束,所以一切都应该没问题。

public class WatchDir {

protected HashSet<File> hashSetOfFiles;
protected String filePath = "";

public WatchDir() {

chooseFilePath();
if (filePath.isEmpty())
return;

listAnfangFiles();

new Thread() {
public void run() {
listNewFiles();
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
}.start();
}

private void listNewFiles() {

File file = new File(filePath);

for (File f : file.listFiles()) {
if (hashSetOfFiles.add(f)) {
newFileFound(f);
}
}
}

private void newFileFound(File f) {

// Hier kommen alle neuen Dateien an
System.out.println(f.getName());
}

private void listAnfangFiles() {

hashSetOfFiles = new HashSet<File>();
File f = new File(filePath);

for (File ff : f.listFiles()) {
hashSetOfFiles.add(ff);
}
}

private void chooseFilePath() {
//
// JFileChooser chooser = new JFileChooser();
// chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//
// if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
// filePath = chooser.getSelectedFile().getAbsolutePath();

filePath = "C:\\Users\\maurice\\Desktop\\Test";
}

public static void main(String[] args) {
new WatchDir();
}
}

最佳答案

    boolean wantToContinue = true;
new Thread() {
public void run() {

while (wantToContinue){
listNewFiles();
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

};
}.start();

使用 boolean 变量。所以你可以从外部控制 Action 。给出真实的条件并不是好的做法。

关于java - 使用连续线程时 JVM 无缘无故关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38804428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com