ThreadPoolExecutor实用程序方法

时间:2012-04-30 17:13:11

标签: java multithreading threadpool

我正在我的multithreading程序中编写一个线程池实用程序。我只需要验证以下方法是否正确,是否为我返回正确的值。我正在使用大小为1的LinkedBlockingQueue。我也是指java文档,它总是说'方法将返回近似'数字短语。所以我怀疑天气跟随条件是否正确。

public boolean isPoolIdle() {
    return myThreadPool.getActiveCount() == 0;
}

public int getAcceptableTaskCount() {
    //initially poolSize is 0 ( after pool executes something it started to change )
    if (myThreadPool.getPoolSize() == 0) {
        return myThreadPool.getCorePoolSize() - myThreadPool.getActiveCount();
    }
    return myThreadPool.getPoolSize() - myThreadPool.getActiveCount();
}

public boolean isPoolReadyToAcceptTasks(){
    return myThreadPool.getActiveCount()<myThreadPool.getCorePoolSize();
}

请告诉我您的想法和建议。

更新

有趣的是,如果pool返回我,getAcceptableTaskCount方法有3个线程可用,当我将3个任务传递给池时,有时一个任务被拒绝,它由RejectedExecutionHandler处理。有时池会处理我通过的所有任务。我想知道为什么池被拒绝任务,因为我根据可用的线程数传递任务。

---------执行灰色答案---

class MyTask implements Runnable {

@Override
public void run() {
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println("exec");
}

}

@Test
public void testTPool(){

    ExecutorService pool = Executors.newFixedThreadPool(5);

    List<Future<MyTask>> list = new ArrayList<Future<MyTask>>();

    for (int i = 0; i < 5; i++) {
        MyTask t = new MyTask();
        list.add(pool.submit(t, t));
    }

    for (int i = 0; i < list.size(); i++) {

        Future<MyTask> t = list.get(i);

        System.out.println("Result -"+t.isDone());

        MyTask m = new MyTask();

        list.add(pool.submit(m,m));
    }
}

这将在控制台中打印Result -false,表示任务未完成。

1 个答案:

答案 0 :(得分:0)

来自您的评论:

  

我需要知道如果池空闲或池可以接受任务。如果池可以接受,我需要知道池中有多少可用线程。如果是5,我将向池中发送5个任务进行处理。

我不认为你应该自己做池会计。对于您的线程池,如果您使用Executors.newFixedThreadPool(5),那么您可以根据需要提交任意数量的任务,它只会在5个线程中运行它们。

  

所以我从向量中获得了前5个任务并将它们分配给了pool.ignore向量中的其他任务,因为它们可以从单独的循环中更新/删除

好的,我明白了。那么您希望最大化并行化,同时不预加载作业?我认为类似下面的伪代码会起作用:

  int numThreads = 5;
  ExecutorService threadPool = Executors.newFixedThreadPool(numThreads);
  List<Future<MyJob>> futures = new ArrayList<Future<MyJob>>();
  // submit the initial jobs
  for (int i = 0; i < numThreads; i++) {
      MyJob myJob = getNextBestJob();
      futures.add(threadPool.submit(myJob, myJob));
  }
  // the list is growing so we use for i
  for (int i = 0; i < futures.size(); i++) {
      // wait for a job to finish
      MyJob myJob = futures.get(i);
      // process the job somehow
      // get the next best job now that the previous one finished
      MyJob nextJob = getNextBestJob();
      if (nextJob != null) {
         // submit the next job unless we are done
         futures.add(threadPool.submit(myJob, myJob));
      }
  }

但是,我并不完全理解线程计数会如何变化。如果您使用更多详细信息编辑问题,我可以调整我的回复。