我有 10 个线程同时填充 10 个表中的唯一代码。每个线程填充数百万条记录。有时7张 table 已经满了,但剩下的3张 table 仍然满了。我想让空闲的 7 个线程与正在运行的 3 个线程同时填充表,这可以做到吗?
String noOfCodes = ""+((Integer.parseInt(totalOfCodes))/10);
ExecutorService executor = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
String threadNo = ""+i;
Runnable worker = new CodeGeneratorDAO(pgmId, digits, points, validity, noOfCodes, product, threadNo);
executor.execute(worker);
resp.setSuccess(true);
}
executor.shutdown();
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
最佳答案
一个简单的解决方案是定义一个 Runnable
来执行比当前 Runnable
更小的任务。分解任务将使整体执行时间变得平滑。
您说您的 Runnable“填充了 1000 条记录”,因此将您的 Runnable 定义为填充 1 条记录,并将所有要更新的 10 * 1000 条记录提交到您的 ExecutorService
:
ExecutorService executor = Executors.newFixedThreadPool(10);
for(Runnable oneRecordRunnable : allRunnables) {
executor.submit(oneRecordRunnable);
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.HOURS);
顺便说一句,我用 awaitTermination
方法替换了消耗 cpu 的 while(true)
循环。
关于java - java中可以使用空闲线程同时执行其他线程的工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24910977/