2016-08-06 22 views
1

我的程序遇到問題。 我想按照他們的結尾對下載的文件進行排序。到目前爲止,我已經有了觀察給定文件路徑並在HashSet中列出這些文件的結構。 現在我的問題是,該程序保持運行幾秒鐘,但隨後退出代碼0結束,所以一切都應該罰款。JVM在無故停止使用線程時關閉

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

回答

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

這不是一個連續的螺紋。 在run()方法中,您沒有允許線程繼續運行的循環條件。
因此sleep(1000);只播放一次,它是您的run()方法中最後播放的指令。在它返回之後,run()方法終止,並且線程因此結束。


編輯:對於具有連續螺紋

例如一個簡單的解決方案,該代碼允許線程永遠不會停止,而是一個過程終止:

new Thread() { 
     public void run() { 

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

     }; 
    }.start(); 

你可以有其他停止循環的條件(延遲,日期或時間,狀態,按下的鍵等)。要允許它,你應該把它放在while()的條件或者的塊中。

+0

好的,謝謝。你會建議做什麼? – mauricemertens

+0

好的,謝謝:) – mauricemertens

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

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

    }; 
}.start(); 

使用布爾變量。所以你可以從外面控制行動。給予真正的條件並不是好的做法。