多线程不是所有的java线程都启动
我在oracle数据库中有大量记录,需要为它们执行一些操作。 应用程序获得4个参数作为输入。它们是“范围从”、“范围到”、“线程数”和“块大小”。 通过使用这些参数,应用程序计算应该为每个线程分配多少条记录。 当一个线程启动时,它从数据库blockSize逐块获取记录,并执行一些操作,然后将记录保存到另一个数据库表中。 我在一台有8个CPU的机器上用10000条记录测试了这个应用程序,并将线程数设置为8。没问题。 在实际环境中,有1000000条记录和16个CPU。通过在那里运行应用程序,并将线程数设置为16或12, 有些线程无法启动。没有错误或异常消息。他们只是从来没有 不要跑。其他线程成功启动。知道吗
下面是代码的一部分:
List list = new ArrayList();
Object[] records;
int allIDsSize = to - from + 1;
int segmentSize = Math.round(allIDsSize % threadsCount == 0 ? allIDsSize / threadsCount : allIDsSize / threadsCount + 1);
Semaphore semaphore = new Semaphore(0);
List<Future> threads = new ArrayList<Future>();
int k = 0;
while (k * segmentSize < allIDsSize) {
int from2 = segmentSize * k + 1;
int to2;
if (from2 + segmentSize - 1 < allIDsSize) {
to2 = from2 + segmentSize - 1;
} else {
to2 = allIDsSize;
}
k++;
MyThread thread = new MyThread(from + from2 - 1, from + to2 - 1, semaphore); //MyThread implements Callable<String>
if (log.isInfoEnabled()) {
log.info(String.format("Thread IDs are from %d to %d", (from + from2 - 1), (from + to2 - 1)));
log.info("thread started " + k);
}
Future<String> future = pool.submit(thread);
threads.add(future);
}
semaphore.acquire(threads.size());
谢谢
索尔马兹
# 1 楼答案
这种情况可能是,一些线程在所有任务都提交到执行器队列之前完成,因此执行器服务不必创建最大数量的线程(固定线程池会根据需要创建新线程,直到达到限制,它不会一次创建所有线程)
作为旁注:对于真正的任务(即
Runnable
或Callable
),使用线程概念(thread
和MyThread
)是令人困惑的