我有10个线程同时在10个表中填充唯一代码。每个帖子填满了百万条记录。有时7张桌子被填满,但其余3张桌子仍在填满。我想放纵免费的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");
答案 0 :(得分:2)
一个简单的解决方案是定义Runnable
执行当前Runnable
的较小任务。分解任务将平滑整个执行时间。
你说你的Runnable&#34;填写了1000条记录&#34;,所以将你的Runnable定义为填写1条记录,并将所有10 * 1000条记录提交给你的ExecutorService
:
ExecutorService executor = Executors.newFixedThreadPool(10);
for(Runnable oneRecordRunnable : allRunnables) {
executor.submit(oneRecordRunnable);
}
executor.shutdown();
executor.awaitTermination(1, TimeUnit.HOURS);
作为旁注,我用while(true)
方法替换了您的cpu-burning awaitTermination
循环。