我正在尝试让线程池执行器工作,我只是想知道我是否在以下代码的某处出错了:
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() 方法,但我看不到这样的东西。
还有为什么有人想要设置最小线程池大小的原因
如有任何帮助/建议,我们将不胜感激。
最佳答案
除非另有说明,否则 ThreadPoolExecutor
使用默认的 ThreadFactory
在同一线程组中创建所有线程。
如果正在运行的线程少于 corePoolSize
,则会创建一个新线程来处理每个传入请求,即使其他工作线程处于空闲状态也是如此。 Keep-alive 不适用于核心线程。创建核心线程后,执行器将仅在队列已满时才创建其他线程(最多 maxPoolSize
)。
如果在存在 maxPoolSize 线程并且队列已满时提交新任务,则该任务将被拒绝。 “拒绝”的行为由 RejectedExecutionHandler
定义。默认情况下,拒绝处理程序是 AbortPolicy
(在拒绝时抛出运行时 RejectedExecutionException)。您应该分析使用这样的策略是否正确,或者设置另一个策略,例如 CallerRunsPolicy
(即在调用了 submit
的线程中运行任务,而不是入队).
关于java - 这是使用 ThreadPoolExecutor 的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15497973/