2

我试图让线程池执行器工作,只是想知道我是否在以下代码的某个地方出错了:

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() 方法,但我看不到这样的东西。

还有任何理由为什么有人想要设置最小线程池大小

任何帮助/建议将不胜感激。

4

1 回答 1

1

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

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

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

于 2013-03-19T11:36:46.147 回答