2011-11-09 17 views
0

我正在使用ThreadPoolExecutor來實現多線程。使用ThreadPoolExecutor時的UI問題

基本上每個線程都分配了一個文件,需要上傳到服務器。 每次成功上傳後,都會從服務器發出通知。

以下代碼生成線程&將文件分配給它們。

Random random = new Random(); 
       ExecutorService executor = new ThreadPoolExecutor(5, 5, 50000L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(400)); 

     int waitTime = 100; 
     while (it.hasNext()) { 

      int time = random.nextInt(1000); 
      waitTime += time; 
      newFile = new File((String) it.next()); 
      executor.execute(new Runnable() { 

       @Override 
       public void run() { 

        processFile(newFile); 
       } 
      }); 
      try { 
       Thread.sleep(waitTime); 
      } catch (Exception e) { 
      } 

     } 

     try { 
      Thread.sleep(waitTime); 
      executor.shutdown(); 
      executor.awaitTermination(waitTime, TimeUnit.MILLISECONDS); 
     } catch (InterruptedException e) { 
     } 

我已經創建了一個用於呈現UI的Java Applet。 每次通知後,我都會更新Java Applet窗口上的文件狀態,其中up​​dateUI()是從processFile()中調用的。

在使用ExecutorService(建議用於處理上述Java v5.0 &上的多線程)之前,我使用Thread類創建線程& wait-notify用於文件上傳功能。顯示每個文件更新狀態的UI在使用Thread類時正確呈現,但在使用ExecutorService時,所有文件都會上傳(功能正常),但UI掛起。

每個文件上傳成功後,需要更新每個文件的文件上傳狀態。

任何建議/提示歡迎。

回答

0

想更新來自非EDT線程的UI(事件線程調用事件處理程序和這樣的),你需要使用SwingUtilities.invokeLater(Runnable)

,你永遠不應該在美國東部時間睡覺或阻止它,因爲這是當一個確保一切響應

但它會更好地使用SwingWorker,因爲這實現了特定於使用後臺線程幾件事情需要更新GUI

與SwingWorker的代碼將出現

while (it.hasNext()) { 

    final File newFile = new File((String) it.next()); 
    SwingWorker<Void,Void> work = new SwingWorker<Void,Void>(){ 

     @Override 
     public Void doInBackground() { 

      processFile(newFile);//do **not** call updateUI() in here 
      return null; 
     } 

     @Override 
     protected void done(){//this gets called after processFile is done on the EDT 
      updateUI(); 
     } 
    }).execute(); 
} 
+0

感謝您的回覆。我想在上傳文件時實現多線程,因此執行程序的實現也很重要。以上代碼不包含任何參考。 – chiranjib

+0

如果你只是消除所有的睡眠和awaitTermination你應該沒問題(你仍然應該關閉執行程序,以避免線程泄漏),只要你沒有超過400個文件(然後添加一個新的作業將失敗) –