这是使用ThreadPoolExecutor的正确方法吗?

时间:2013-03-19 11:16:23

标签: java multithreading concurrency executor

我正在尝试让线程池执行器工作,我只是想知道我是否在某处出现了以下代码:

public class testPool implements Runnable {

    static Executor pooledExecutor = null;
    private Threat thread = null;

    private testPool(int minThreadPoolSize,
                     int initThreadPoolSize,
                     int maxThreadPoolSize,
                     int threadKeepAliveTime,
                     int queueCapacity) throws Exception {

        pooledExecutor = new ThreadPoolExecutor(initThreadPoolSize,
                                    maxThreadPoolSize,
                                    (long) (1000 * threadKeepAliveTime),
                                    TimeUnit.MILLISECONDS,
                                    new LinkedBlockingQueue<Runnable>(queueCapacity));

        this.thread = new Thread(this);
        this.thread.setName("testThread");

        try {
              this.thread.setDaemon(true);
        } catch (Exception e) {
           // DO Something
        }
    }

    public void run() {
         while(true){
            try {
                // code to get a testobject
                pooledExecutor.execute(testObject);
             } catch (Exception e) {
                 //Do something
             } finally {
              //if shutdown parameter is true
              break
            }
          }
      }

 }

基本上,我不确定这个实现是否会实际创建线程?或者我需要使用线程工厂吗?在我使用pooledexecuter之前,它有一个createThreads()方法,但我看不到这样的东西。

也有人为什么要设置最小线程池大小

非常感谢任何帮助/建议。

1 个答案:

答案 0 :(得分:1)

除非另有说明,否则ThreadPoolExecutor使用默认ThreadFactory来创建同一线程组中的所有线程。

如果正在运行少于corePoolSize个线程,则会创建一个新线程来处理每个传入请求,即使其他工作线程处于空闲状态也是如此。 Keep-alive不适用于核心线程。创建核心线程后,执行程序仅在队列已满时才会创建其他线程(最多maxPoolSize

如果在maxPoolSize线程有队列已满时提交了新任务,则该任务将被拒绝。 “拒绝”的行为由RejectedExecutionHandler定义。默认情况下,拒绝处理程序为AbortPolicy(拒绝时抛出运行时RejectedExecutionException)。您应该分析使用此类策略是否正确,或者可能设置另一个例如CallerRunsPolicy(即在已调用submit的线程中运行任务,而不是排队)。

相关问题