java判断线程池,如何判断Java线程池中是否有可用线程

本文讨论如何有效地使用固定大小的线程池来处理数据库任务,确保不会超过指定的线程数量。建议提交Runnable对象给ExecutorService,让它自动管理线程,而不是直接提交Thread。示例代码展示了如何在所有线程忙碌时让新任务等待,避免主线程睡眠,同时提供了一种超时等待的任务完成策略。

I am trying to proccess a queue of tasks from a database table as fast as possible while also limiting the number of threads to process the tasks.

I am using a fixed sized thread pool with Executors.newFixedThreadPool(N);

I want to know if there is a way of knowing if the thread pool is full, by that I mean are there currently 50 threads running, if so then I'll wait for a thread to be available before starting a new one instead of sleeping the main thread.

Code of what I would like to do:

ExecutorService executor = Executors.newFixedThreadPool(N);

ResultSet results;

while( true ) {

results = getWaitingTasksStmt.executeQuery();

while( results.next() && executor.notFull() ) {

executor.submit( new thread( new runnableInheritedClass(results) ) );

}

}

解决方案

You should not submit a Thread object to the executor, that negates its entire purpose. You should submit Runnable objects and let the Executor worry about the Thread handling. It will automatically queue up your Runnables when all threads are busy and when one task is complete it will grab a waiting task from the queue.

So your code should look more like this:

ExecutorService executor = Executors.newFixedThreadPool(N);

ResultSet results = getWaitingTasksStmt.executeQuery();

while( results.next() ) {

executor.submit(new RunnableInheritedClass(results) ) );

}

executor.shutdown();

executor.awaitTermination(10, TimeUnit.MINUTES);

This will allow 10 minutes for all tasks to complete, adjust as neccesary for your situatioin. Waiting forever is discouraged so think of some kind of reasonable timeout for your tasks.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值