java - 执行者没有按预期处理任务

标签 java concurrency executor

如果我运行持久任务,如果第一个任务没有完成,Executor 永远不会启动新线程。有人可以帮助我了解为什么以及如何解决这个问题吗?

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.junit.Test;

public class TestExecutor {

    @Test
    public void test() throws InterruptedException {
        ExecutorService checkTasksExecutorService = new ThreadPoolExecutor(1, 10,
                100000, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());

        for (int i = 0; i < 20; i++) {
            checkTasksExecutorService.execute(new Runnable() {

                public  void run(){
                    try {
                        System.out.println(Thread.currentThread().getName() + "   running!");
                        Thread.sleep(10000);
                    } catch (Exception e) {
                    }

                }
            });
        }

        Thread.sleep(1000000);
    }
}

最佳答案

这是由文档解决的:

When a new task is submitted in method execute(java.lang.Runnable), and fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle. If there are more than corePoolSize but less than maximumPoolSize threads running, a new thread will be created only if the queue is full.

因此,要实现您想要的行为,要么增加 corePoolSize,要么为执行程序服务提供一个不可增长的队列,如下所示:

ExecutorService checkTasksExecutorService = new ThreadPoolExecutor(1, 20,
    100000, TimeUnit.MILLISECONDS,
    new SynchronousQueue<Runnable>());

关于java - 执行者没有按预期处理任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17898922/

相关文章:

java - 如果有注释,则在成员变量之前换行

java - 如何返回已在 4 个不同线程中编辑过的变量的一个实例?

java - 我需要将标志放入同步块(synchronized block)中吗?

java - RecursiveTask 线程不会被 join() 阻塞

spring - spring executor中java executor framework的invokeAll等价方法

java - 如何解析改造模型类中的数组值数组?

java - 命名单元和集成测试方法的最佳实践?

java - 尝试/捕获错误

java - 捕获并行线程的总执行时间

java - 我必须在应用程序退出时手动关闭 Executor 吗?