我正在编写一个定制的ThreadPoolExecutor,其附加功能如下:
我重写了ThreadPoolExecutor版本java1.5的执行方法。
新守则如下:
public void execute(Runnable command) {
System.out.println(" Active Count: "+getActiveCount()+" PoolSize: "+getPoolSize()+" Idle Count: "+(getPoolSize()-getActiveCount())+" Queue Size: "+getQueue().size());
if (command == null)
throw new NullPointerException();
for (;;) {
if (runState != RUNNING) {
reject(command);
return;
}
if (poolSize < corePoolSize && addIfUnderCorePoolSize(command)) {
return;
}
if (runState == RUNNING && (getPoolSize()-getActiveCount() != 0) && workQueue.offer(command)) {
return;
}
int status = addIfUnderMaximumPoolSize(command);
if (status > 0) // created new thread
return;
if (status == 0) { // failed to create thread
reject(command);
return;
}
if (workQueue.offer(command))
return;
// Retry if created a new thread but it is busy with another task
}
}遗留代码如下:
public void execute(Runnable command) {
if (command == null)
throw new NullPointerException();
for (;;) {
if (runState != RUNNING) {
reject(command);
return;
}
if (poolSize < corePoolSize && addIfUnderCorePoolSize(command))
return;
if (workQueue.offer(command))
return;
int status = addIfUnderMaximumPoolSize(command);
if (status > 0) // created new thread
return;
if (status == 0) { // failed to create thread
reject(command);
return;
}
// Retry if created a new thread but it is busy with another task
}
}现在正在生成的问题是,当线程处于空闲状态时,它不会创建新线程,但是它甚至不会将任务分配给这些线程,而是将它们添加到队列中,这是不需要的,因为我们不希望任务等待,而是尽快处理它,即使它需要新的线程创建,但是任务不允许等待。
请帮我解决这个问题。谢谢。
发布于 2013-10-22 21:46:17
如果我理解这个问题,我相信我已经找到了ThreadPoolExecutor默认行为的解决方案,我在这里的回答中显示了这一点:
基本上,您可以让LinkedBlockingQueue为queue.offer(...)返回false,这将在必要时向池中添加一个额外的线程。如果池已经位于最大线程,并且它们都很忙,那么将调用RejectedExecutionHandler。然后是处理程序将put(...)放入队列中。
看看我的密码。
发布于 2013-10-10 17:54:29
根据我对您所描述的三种功能的了解,我认为使用ExectuorService将比您目前试图做的工作做得更多:提供管理终止的方法的Executor和能够产生跟踪一个或多个异步任务进度的未来的方法,特别是:
1.捕获线程池:允许创建所需的多个线程,以并行方式执行任务。旧的可用线程将用于新任务和固定线程池。
2.固定线程池:提供一个具有固定线程数的池。如果线程不可用于该任务,则将该任务置于队列中,等待另一个任务结束。
看看这篇文章,得到详细的解释和很好的例子。
https://stackoverflow.com/questions/19302337
复制相似问题