问题1. 不太好描述,直接看代码吧
public class QueueConsumer extends EndPoint implements Runnable {
// 线程池
private ExecutorService executor = null;
public QueueConsumer(String endPointName, String hosts, String ports,
String username, String password) throws Exception {
super(endPointName, hosts, ports, username, password);
// 初始化线程池
executor = Executors.newCachedThreadPool();
}
@Override
public void run() {
try {
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(endPointName, false, consumer);
while (true) {
// 信息到达时
Delivery delivery = consumer.nextDelivery();
// 初始化业务线程对象
BusinessClient businessClient = new BusinessClient(channel, delivery);
// 执行任务
executor.execute(businessClient);
}
} catch (Exception e) {
LogUtil.printException("消息队列异常", e, LogUtil.LOG_LEVEL_ERROR);
} finally {
try {
close();
} catch (Exception e) {
LogUtil.printException("关闭消息队列异常", e, LogUtil.LOG_LEVEL_ERROR);
}
}
}
}
public class BusinessClient implements Runnable {
... 省略
// 主要代码
List<Callable<Object>> taskList = new ArrayList<Callable<Object>>();
for (BaseRequestData<BaseResponseData> queryData : queryDataLst) {
QueryThread queryThread = new QueryThread(queryData);
taskList.add(queryThread);
}
// 问题点:此处使用Executors.newFixedThreadPool(i)会抛出IllegalArgumentException
但是使用Executors.newCachedThreadPool()则不会有问题.不是很理解,为什么此处不可以用newFixedThreadPool(i)?
ExecutorService executor = Executors.newCachedThreadPool();
List<Future<Object>> results = executor.invokeAll(taskList);
executor.shutdown();
... 省略
}
问题2. 我如果定义一个线程池工厂,将线程池定义为static final,每个需要并发的地方都使用工厂来获得线程池,
那么问题来了,我这个线程池会自动扩展或者释放线程吗?
纯粹自学的Java, 对于一些基础知识不是很理解,望不吝赐教!谢谢
怪我咯2017-04-18 09:57:58
1, Executors.newFixedThreadPool(nThreads ):IllegalArgumentException - if nThreads <= 0
2, final
은 스레드 풀 주소가 변경되지 않지만 스레드 풀의 스레드에 제한이 없음을 의미합니다.
PHPz2017-04-18 09:57:58
Executors.newFixedThreadPool(i)
여기서 i
의 값 범위가 잘못되었죠? IllegalArgumentException
을 보면 0
보다 값이 작다는 의미이므로 허용되지 않습니다.
Executors.newFixedThreadPool(i)
결국 다음과 같은 논리가 따르게 됩니다.