package com.icheetor.thread.test;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import com.google.common.base.Objects;
/**
* 验证线程池扩展能力的方法
* @author iCheetor
*
*/
public class TestThreadPool {
private static 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);
}
}
/**
* 如果任务数小于Max_size,那么只会创建任务数量个线程,如果任务数大于Max_size,那么最多创建Max_size个线程
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
final TestingThreadFactory factory = new TestingThreadFactory();
int Max_size = 10;
ExecutorService exec = Executors.newFixedThreadPool(Max_size,factory);
for(int i = 0; i < 5; i ++) {
exec.execute(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
for(int i = 0; i < 20 && factory.numCreated.get() < Max_size; i ++){
Thread.sleep(100);
}
System.out.println(factory.numCreated.get());
if(Objects.equal(factory.numCreated.get(), Max_size)) {
System.out.println("equal");
}
exec.shutdownNow();
}
}