【问题标题】:How to tell if there is an available thread in a thread pool in java如何判断java线程池中是否有可用线程
【发布时间】:2011-02-09 02:54:20
【问题描述】:

我正在尝试尽快处理来自数据库表的任务队列,同时限制处理任务的线程数。
我正在使用带有 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) ) );
    }
}

【问题讨论】:

  • 执行器创建线程。你应该把runnables/callables放在那里。如果 N 设置为 50 并且 50 是您的限制,则固定线程池不会创建新线程。

标签: java multithreading threadpool


【解决方案1】:

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

所以你的代码应该看起来更像这样:

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 分钟完成所有任务,根据您的情况进行调整。不鼓励永远等待,因此请为您的任务考虑某种合理的超时时间。

【讨论】:

    【解决方案2】:

    ExecutorService 为您完成所有工作。如果所有线程当前都被其他任务使用,则新任务将被放入队列并稍后处理。即使当前正在使用所有线程,您的主线程也不会在提交新任务时阻塞。

    ExecutorService executor = Executors.newFixedThreadPool(N);
    ResultSet results;
    
    while( true ) {
        results = getWaitingTasksStmt.executeQuery();
    
        while( results.next() ) {
            // If all threads are in use, the new task will be queued
            executor.submit( new runnableInheritedClass(results) );
        }
    

    【讨论】:

      猜你喜欢
      • 2019-08-28
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多