2017-04-19 35 views
4

我用例:如何創建一個ThreadPoolExecutor,根據需要創建線程並在適用時將其過期?

  • 設置最小大小「N」對於這意味着「N」螺紋總是執行人啓動後的可用線程池。
  • 設置線程池的最大大小'M'。
  • 當所有'M'線程忙時,傳入任務應該排隊。
  • 基於空閒狀態超時期滿(M-N)線程。

我相信HttpClient後面的池管理器可能有類似的設置。我試圖用ThreadPoolExecutor來實現它,但無法找到一種方法。可能嗎?

這是一個測試的例子。

public class ExecutorExample { 

    public static void main(String[] args) throws InterruptedException { 
     int minPoolSize = 2; 
     int maxPoolSize = 10; 
     int ttlMillis = 100; 
     ThreadPoolExecutor startupExecutor = new ThreadPoolExecutor(minPoolSize, 
       maxPoolSize, // surprisingly this is not obeyed. 
       ttlMillis, 
       TimeUnit.MILLISECONDS, 
       new LinkedBlockingQueue<Runnable>()); 

     for (int i = 0; i < 20; i++) { 
      System.out.println(Thread.currentThread().getName() + ":" + startupExecutor.getCorePoolSize()); 
      startupExecutor.execute(new MyRunnable(i)); 
     } 

     for (int i = 0; i < 20; i++) { 
      Thread.sleep(1000); 
      System.out.println(Thread.currentThread().getName() + ":" + startupExecutor.getCorePoolSize()); 
     } 
    } 

} 

class MyRunnable implements Runnable { 

    int n; 

    public MyRunnable(int n) { 
     this.n = n; 
    } 

    @Override 
    public void run() { 
     try { 
      Thread.sleep(2000); 
      System.out.println(Thread.currentThread().getName() + ":" + n); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 

    } 

} 
+1

'ThreadPoolExecutor(corePoolSize,maximumPoolSize,keepAliveTime,unit,workQueue)'是否符合您的需求? –

+0

@RomanPuchkovskiy你想到哪個隊列對象?我會測試。 – phani

+0

這是一個奇怪的要求......爲什麼在傳入任務排隊之前,需要將線程數從N增加到M *? –

回答

0

如何:

 ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); 

ThreadPoolExecutor

編輯:通常我用的隊列是有界阻塞隊列。

BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(queueCapacity, true); 

EDIT2:最大池大小隻在隊列滿時啓動。由於您使用的是無界隊列,因此線程數不會超過2. Se鏈接位於下方。

rules-of-a-threadpoolexecutor-pool-size

認沽尺寸1,你會看到其中的差別。

new LinkedBlockingQueue<>(1)); 

編輯3:在您的例子改變startupExecutor.getCorePoolSize()startupExecutor.getPoolSize()

+0

我不會在超時後過期線程。你能用真正的Queue實現來更新它嗎? – phani

+0

你的意思是在線程執行完之後到期嗎? –

+0

在超時後終止空閒線程(顯然,由於線程空閒,隊列爲空)。我發佈了一些示例代碼來測試您的ThreadPoolExecutor。 – phani

相關問題