java中如何判断线程池中是否有可用线程
我正在尝试尽快处理数据库表中的任务队列,同时还限制处理任务的线程数。
我正在使用固定大小的线程池 Executors.newFixedThreadPool(N);
我想知道是否有办法知道线程池是否已满,我的意思是当前有 50 个线程正在运行,如果是这样,那么我将等待一个线程可用,然后再启动一个新线程,而不是休眠主线程。
我想做的事情的代码:
ExecutorService executor = Executors.newFixedThreadPool(N);
ResultSet results;
while( true ) {
results = getWaitingTasksStmt.executeQuery();
while( results.next() && executor.notFull() ) {
executor.submit( new thread( new runnableInheritedClass(results) ) );
}
}
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) ) );
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不应该向执行器提交 Thread 对象,这会抵消其全部目的。您应该提交
Runnable
对象并让Executor
担心Thread
处理。当所有线程都忙时,它会自动将您的 Runnable 排队,当一个任务完成时,它会从队列中获取一个正在等待的任务。所以你的代码应该看起来更像这样:
这将允许 10 分钟完成所有任务,根据你的情况进行必要的调整。不鼓励永远等待,因此请为您的任务考虑某种合理的超时。
You should not submit a
Thread
object to the executor, that negates its entire purpose. You should submitRunnable
objects and let theExecutor
worry about theThread
handling. It will automatically queue up yourRunnable
s 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:
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.
ExecutorService
会为您完成所有工作。如果所有线程当前都被其他任务使用,则新任务将被放入队列中并在稍后的时间进行处理。即使当前所有线程都在使用,您的主线程在提交新任务时也不会阻塞。The
ExecutorService
does all that work for you. If all of the threads are currently being used by other tasks, the new tasks will be placed into a queue and processed at some later time. Your main thread will not block when submitting a new task even if all the threads are currently being used.