gpt4 book ai didi

java - ThreadFactory newThread() 方法对于 ThreadPoolExectutor 中的每个submit() 调用仅调用一次

转载 作者:行者123 更新时间:2023-12-02 04:01:22 26 4
gpt4 key购买 nike

我试图为提交给 ThreadPoolExecutor 的每个 MyRunnable 分配一个编号,但没有成功。

我的代码片段:

import java.util.concurrent.*;

class SimpleThreadFactory implements ThreadFactory {
String name;
static int threadNo = 0;

public SimpleThreadFactory (String name){
this.name = name;
}
public Thread newThread(Runnable r) {
++threadNo;
System.out.println("thread no:"+threadNo);
return new Thread(r,name+":"+threadNo );
}
public static void main(String args[]){
SimpleThreadFactory factory = new SimpleThreadFactory("Ravindra");
ThreadPoolExecutor executor = new ThreadPoolExecutor(1,5,10,TimeUnit.SECONDS,new ArrayBlockingQueue(100),factory);
for ( int i=0; i < 10; i++){
executor.submit(new MyRunnable());
}
executor.shutdown();
}
}

class MyRunnable implements Runnable {
public void run(){
System.out.println("Runnable:"+Thread.currentThread().getName());
}
}

我的期望:

executor.submit(new MyRunnable()); 应为执行器上的每个提交调用 ThreadFactory 中的 newThread。但实际上,这种事只发生过一次。

输出:

thread no:1
Runnable:Ravindra:1
Runnable:Ravindra:1
Runnable:Ravindra:1
Runnable:Ravindra:1
Runnable:Ravindra:1
Runnable:Ravindra:1
Runnable:Ravindra:1
Runnable:Ravindra:1
Runnable:Ravindra:1
Runnable:Ravindra:1

为什么submit()没有为每个提交的Runnable任务创建新线程?

如何为提交给执行器的每个 MyRunnable 分配序列号?

提前致谢

最佳答案

问题在于 CorePoolSize 和队列之间的交互。

来自Javadoc

"If corePoolSize or more threads are running, the Executor always prefers queuing a request rather than adding a new thread."

"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 中有空间(即当前正在执行的任务完成时),因此当前您永远不会使用超过 1 个线程。

关于java - ThreadFactory newThread() 方法对于 ThreadPoolExectutor 中的每个submit() 调用仅调用一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34857723/

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