2017-06-22 78 views
0

我正在研究一個基於Java的程序,該程序從文件讀取並將每行發送到其自己的處理Runnable中以執行一些單線程計算。我正在使用一個固定的線程池,每個可用內核有一個任務來並行化這個。該文件非常龐大,在提交作業時無法將每個文件加載到內存中。是否有可能讓主線程(即提交這些任務)暫停直到線程池中的線程變爲可用?修復線程池:暫停直到線程可用?

+0

**是否有可能有主線程(即提交這些任務)暫停直到線程池中的線程變爲可用**它甚至不可能任何人說沒有代碼的東西? – ShayHaned

回答

1

創建一個簡單的線程池,其可用工作線程與池大小相同。提交前檢查是否有可用線程,然後提交else等待鎖定。

你也可以使用Semaphore,它會阻塞,直到acquire()會獲得一些價值。 信號燈exanple:簡單的線程池的

Semaphore semaphore = new Semaphore(pool_size); 

//critical section 
semaphore.acquire(); 

... 

semaphore.release(); 

例子:

private List<WorkerThread> workers; 
     private LinkedList<WorkerThread> availWorkers = new LinkedList<WorkerThread>(); 
     private LinkedList<WorkerThread> busyWorkers = new LinkedList<WorkerThread>(); 

提交方法

public boolean submit(Runnable runnable) { 
      if (runnable == null) { 
       return false; 
      } 

      synchronized (Lock) { 

       handoffPending = true; 

       // Wait until a worker thread is available 
       while ((availWorkers.size() < 1) && !isShutdown) { 
        try { 
         Lock.wait(500); 
        } catch (InterruptedException ignore) { 
        } 
       } 

       if (!isShutdown) { 
        WorkerThread wt = (WorkerThread)availWorkers.removeFirst(); 
        busyWorkers.add(wt); 
        wt.run(runnable); 
       } else { 
        // If the thread pool is going down, execute the Runnable 
        // within a new additional worker thread (no thread from the pool). 
        WorkerThread wt = new WorkerThread(this, threadGroup, 
          "WorkerThread-LastJob", prio, isMakeThreadsDaemons(), runnable); 
        busyWorkers.add(wt); 
        workers.add(wt); 
        wt.start(); 
       } 
       Lock.notifyAll(); 

      } 

      return true; 
     }