2011-05-19 92 views
-1

我有一臺服務器,根據請求發送不同的文件(每個打開一個線程)。 每個線程都不知道他在創建時處理哪個文件,但只有收到一個帶有其名稱的消息時,所以當時我需要以某種方式將它與該文件相關聯。Java:如何存儲處理不同文件的多個線程

我需要選擇等待某個文件的所有線程結束,當然還有 服務器中的所有線程。

整個線程的事情是由一個線程組完成的, 至於文件,我想爲每個文件添加一個線程列表(我已經有一個包裝類),並添加選項以等待某個文件。 但我不認爲這是一個好的解決方案,再加上我需要使用一些併發的集合,我無法找到任何只是一個併發鏈表。

任何建議如何實現?

+2

我不明白你的問題。你想要做什麼?爲什麼多個線程在同一個文件上工作?你在使用SSD磁盤嗎?解釋真正的問題是什麼,而不是你如何試圖解決它。 – Kaj 2011-05-19 15:06:19

+1

你在尋找Thread.join()嗎? – 2011-05-19 15:11:16

+0

考慮使用java.util.concurrent.CountDownLatch – happymeal 2011-05-19 15:14:24

回答

0

我需要的選項等待所有特定文件的 線程結束

我沒有清楚地瞭解你的需求,但我認爲這樣的事情會爲你工作:

// FileSender is the wrapper class you mentioned - where you keep track 
// of file->threads association 
public class FileSender { 
    private final File file; 

    private List<Thread> threads = new ArrayList<Thread>(); 

    public FileSender(File file) { 
     this.file = file; 
    } 

    public void addThread(Thread thread) { 
     if (thread != null) { 
      this.threads.add(thread); 
     } 
     for (Iterator<Thread> itr = threads.listIterator(); itr.hasNext();) { 
      Thread t = itr.next(); 
      if (! t.isAlive()) { 
       itr.remove(); 
      } 
     } 
    } 

    // this method blocks until all threads associated with 
    // this file has completed execution 
    public void waitForCompletion() throws InterruptedException { 

     for (Iterator<Thread> itr = threads.listIterator(); itr.hasNext();) { 
      Thread thread = itr.next(); 
      thread.join(); 
      itr.remove(); 
     } 
    } 
}