java并发编程实战中第12章 12.1.3中验证线程池扩展能力的测试方法:
原例中有个bug:
代码中没有给newFixedThreadPool()传递threadFactory对象,所以怎么运行threadFactory.numCreated.get()都是0.
正确代码(可直接运行):
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
public class TestingThreadFactory implements ThreadFactory{
public final AtomicInteger numCreated = new AtomicInteger();
private final ThreadFactory factory = Executors.defaultThreadFactory();
@Override
public Thread newThread(Runnable r) {
numCreated.incrementAndGet();
return factory.newThread(r);
}
public static void main(String[] args) throws Exception {
TestingThreadFactory threadFactory = new TestingThreadFactory();
int MAX_SIZE = 10;
ExecutorService exec = Executors.newFixedThreadPool(MAX_SIZE,threadFactory);
for (int i = 0; i < 10 * MAX_SIZE; i++) {
exec.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
});
}
for (int i = 0; i < 20 && threadFactory.numCreated.get() < MAX_SIZE; i++) {
Thread.sleep(100);
}
System.out.println(threadFactory.numCreated.get());
exec.shutdown();
}
}
因为newFixedThreadPool是定长线程池,不能扩展,所以如果任务数小于MAX_SIZE,那么只会创建任务数量个线程,如果任务数大于MAX_SIZE,那么最多创建MAX_SIZE个线程。
最后i < 20 && threadFactory.numCreated.get() < MAX_SIZE 是为了保证线程池中的已经有足够数量的任务执行了execute(或运行中或等待中),要求2秒后停止等待,或者当运行中的线程数量超过了MAX_SIZE,表明当前线程池有扩展的能力,所以也会停止等待,继续执行。
参考: 验证线程池扩展能力的测试方法_iCheetor-CSDN博客
|