如何判断Java线程池中是否有可用线程 [英] How to tell if there is an available thread in a thread pool in java

查看:2459
本文介绍了如何判断Java线程池中是否有可用线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从数据库表中尽可能快地处理任务队列,同时还限制了处理任务的线程数.
我正在使用具有 Executors.newFixedThreadPool(N);

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);

我想知道是否有一种方法可以知道线程池是否已满,也就是说我当前有50个线程在运行,如果是这样,那么我将在启动新线程之前等待线程可用而不是休眠主线程.

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.

我想做的事情的代码:

ExecutorService executor = Executors.newFixedThreadPool(N);
ResultSet results;

while( true ) {
    results = getWaitingTasksStmt.executeQuery();

    while( results.next() && executor.notFull() ) {
        executor.submit( new thread( new runnableInheritedClass(results) ) );
    }
}

推荐答案

您不应将Thread对象提交给执行者,这会抵消其全部目的.您应该提交Runnable对象,并让Executor担心Thread处理.当所有线程繁忙时,它将自动将您的Runnable排队,并且当一个任务完成时,它将从队列中抓取一个等待的任务.

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);

这将需要10分钟才能完成所有任务,并根据您的情况进行调整.不建议永远等待,因此请为您的任务考虑某种合理的超时时间.

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.

这篇关于如何判断Java线程池中是否有可用线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆