newFixedThreadPool.setCorePoolSize() 不使用线程,创建新的线程。
说明:我为大小 2 创建了一个 newFixedThreadPool,如果这个池的两个线程都忙,我使用 setCorePoolSize() 向这个池中添加两个线程。在这个过程中,它似乎没有重用线程,或者可能正在终止一些线程并创建新的线程,我将用代码来解释。
代码:(请参阅输出了解)
public class IncreasePoolSize
{
static ExecutorService service = null;
public static void main(String[] args) throws JMSException, InterruptedException
{
int NoOfth = 2;
int noOfTimesToInc = 0;
System.out.println("Start");
service = Executors.newFixedThreadPool(NoOfth);
for (;;)
{
if ( ((ThreadPoolExecutor)service).getActiveCount() >= NoOfth )
{
if (noOfTimesToInc < 1)
{
System.out.println("Increased Threads-" + (noOfTimesToInc + 1) + " time(s)");
NoOfth += 2;
System.out.println("NoOfTh-" + NoOfth);
((ThreadPoolExecutor)service).setCorePoolSize(NoOfth);
System.out.println("Total no of theads after increasing-" + ((ThreadPoolExecutor)service).getCorePoolSize());
noOfTimesToInc++;
}
}
else if ( ((ThreadPoolExecutor)service).getActiveCount() <= NoOfth)
{
service.execute(new ConcreteThread());
}
}
}
}
class ConcreteThread implements Runnable
{
public void run()
{
try
{
System.out.println("Thread No-" + Thread.currentThread().getId());
Thread.sleep(5000);
System.out.println("Thread No-" + Thread.currentThread().getId() + " finished");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
一旦线程 11 和 12 开始工作,在输出中可以看到,我将数字增加 2,因此线程 13 和 14 开始工作,但之后,我总是创建新线程而不是使用线程 11 和 12 并重用线程 13和 14。
输出:(已在调试模式下运行)
Start
Thread No-11
Thread No-12
Increased Threads-1 time(s)
NoOfTh-4
Total no of theads after increasing-4
Thread No-13
Thread No-14
Thread No-11 finished
Thread No-12 finished
Thread No-13 finished
Thread No-14 finished
Thread No-15
Thread No-16
Thread No-13
Thread No-14
Thread No-15 finished
Thread No-16 finished
Thread No-13 finished
Thread No-14 finished
Thread No-17
Thread No-18
Thread No-13
Thread No-14
Thread No-17 finished
Thread No-18 finished
Thread No-13 finished
Thread No-14 finished
Thread No-19
Thread No-20
Thread No-13
Thread No-14
Thread No-19 finished
Thread No-20 finished
Thread No-13 finished
Thread No-14 finished
Thread No-21
Thread No-22
Thread No-13
Thread No-14
Thread No-21 finished
Thread No-22 finished
Thread No-13 finished
Thread No-14 finished
Thread No-23
Thread No-24
Thread No-13
Thread No-14