gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:16:19 25 4
gpt4 key购买 nike

如果我运行持久任务,如果第一个任务没有完成,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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com