2012-10-18 19 views
1

我有一個要求,我必須檢查文件夾中是否存在任何文件。如果是,那麼我需要逐一處理它。有了我的基礎知識,我已經到達了我在下面發佈的代碼結構。使用java在n秒內檢查並處理一次

我創建了一個無限循環並檢查文件是否存在於該文件夾中。如果是,那麼我創建一個線程並處理它,否則它會等待一分鐘並再次檢查。

class sample {  
    synchronized int getNoOfFiles() { 
     // get number of files in the folder 
    }  
    synchronized void openFile() { 
     // open one file 
    } 
    synchronized void getFileContents() { 
     // get the file content 
    } 
    synchronized void processFileContent() { 
     //performing some operation on file contents 
    }  
    synchronized void closeFile() { 
     //closing the file 
    }  
    synchronized void deleteFile() { 
     //delete the file 
    } 

}  
class Test {  
    public static void main(String args[]) { 
     int flag=0; 
     Sample obj = new Sample(); 
     while(1) { 
      flag = obj.getNoOfFiles();  
      if(flag) { 
       for(i=0;i<flag;i++) { 
        MyThread1 t1 = new MyThread1() { 
         public void run() { 
          obj.openFile(); 
          obj.getFileContents(); 
          obj.processFileContent(); 
          obj.closeFile(); 
          obj.deleteFile(); 
         } 
        };  
        t1.start(); 
       } 
      } 
      else { 
       try { 
        Thread.sleep(60000); 
       } 
      }  
     } 
    }  
} 
+1

線程沒有得到垃圾收集。所以你的代碼已經在每個循環中創建一個新的線程。即使't1'引用了仍在處理文件的線程,該線程也不會停止運行。一個新的將被實例化,由't1'引用並開始。 – Tobold

+0

噢。所以,我不需要這個for循環(剛剛編輯代碼)。我怎麼能阻止線程創建,直到一個線程完成整個過程。你能幫我嗎 – srinath

+0

你爲什麼要這麼做?如果你創建一個線程,然後等待線程完成,爲什麼要使用併發呢? – Tobold

回答

2

我會建議使用ScheduledExecutorService

ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1); 
executor.scheduleAtFixedRate(new Runnable() { 
     public void run() 
     { 
      obj.openFile(); 
      obj.getFileContents(); 
      obj.processFileContent(); 
      obj.closeFile(); 
      obj.deleteFile(); 
     } 
    }, 0, 1, TimeUnit.MINUTES); 
3

而是自己做這種事情的,我建議你去看看Timer類,可以用來做經常性的任務。因爲手動亂搞線程往往會導致怪異的錯誤。

更好的是ScheduledThreadPoolExecutor但如果您以前從未使用過執行程序,它可能會有點複雜。有關如何操作,請參閱Keppil的答案。

兩者之間的差異很好地總結在這裏:Java Timer vs ExecutorService?