java - java中可以使用空闲线程同时执行其他线程的工作吗?

标签 java multithreading

我有 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/

相关文章:

python - Python 的垃圾收集器会损害我的应用程序吗?

java - Android 自定义 facebook 按钮,图标无法正确加载

java - Aop调用异常 : in @Autowieired in JUnit

java - Dropbox Java : Use Proxy with authentication

java - 无法在android中循环使用Toast消息

ruby - 为什么 Ruby 中没有竞争条件

Java String.replaceFirst() 问题

java - Spring DATA JPA 以 Hibernate 作为 JPA 提供者

java - Android Ping 命令在无法访问的服务器上死机

c++ - 请推荐一本关于使用 boost.thread 或 C++11 进行多线程处理的有值(value)的书