2017-04-19 34 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

相关问题