上述是线程池处理任务的流程,相信大家都在网上搜到不少,今天咱们来用代码验证一下,亲自看看这个流程是不是这样的
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.*;
@Slf4j
public class Test {
private static ExecutorService service;
public static ObjectMapper objectMapper = new ObjectMapper();
static {
ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("demo-pool-%d").build();
//核心线程2个,最大线程4个,存活时间20秒,队列最大长度为2,
service = new ThreadPoolExecutor(2, 4, 20, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2), threadFactory);
}
public static void main(String[] args) throws JsonProcessingException, InterruptedException {
for (int i = 0; i < 5; i++) {
//每次等待50毫秒,确保前一个任务可以提交
TimeUnit.MILLISECONDS.sleep(50);
int finalI = i;
service.execute(() -> {
try {
//打印当前执行任务的线程名字和任务id
log.info(finalI + "-----" + Thread.currentThread().getName() + "-------before");
TimeUnit.SECONDS.sleep(10);
log.info(finalI + "-----" + Thread.currentThread().getName() + "-------after");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
}
}
}
上述代码打印结果如下:
2020-10-30 22:07:36.051 INFO [demo-pool-0]com.tomorrowsg.test.test.Test.lambda0:40 -0-----demo-pool-0-------before
2020-10-30 22:07:36.100 INFO [demo-pool-1]com.tomorrowsg.test.test.Test.lambda0:40 -1-----demo-pool-1-------before
2020-10-30 22:07:36.252 INFO [demo-pool-2]com.tomorrowsg.test.test.Test.lambda0:40 -4-----demo-pool-2-------before
2020-10-30 22:07:46.055 INFO [demo-pool-0]com.tomorrowsg.test.test.Test.lambda0:42 -0-----demo-pool-0-------after
2020-10-30 22:07:46.056 INFO [demo-pool-0]com.tomorrowsg.test.test.Test.lambda0:40 -2-----demo-pool-0-------before
2020-10-30 22:07:46.101 INFO [demo-pool-1]com.tomorrowsg.test.test.Test.lambda0:42 -1-----demo-pool-1-------after
2020-10-30 22:07:46.101 INFO [demo-pool-1]com.tomorrowsg.test.test.Test.lambda0:40 -3-----demo-pool-1-------before
2020-10-30 22:07:46.252 INFO [demo-pool-2]com.tomorrowsg.test.test.Test.lambda0:42 -4-----demo-pool-2-------after
2020-10-30 22:07:56.058 INFO [demo-pool-0]com.tomorrowsg.test.test.Test.lambda0:42 -2-----demo-pool-0-------after
2020-10-30 22:07:56.102 INFO [demo-pool-1]com.tomorrowsg.test.test.Test.lambda0:42 -3-----demo-pool-1-------after
从上面可以看出,
线程池两个核心线程(demo-pool-0、demo-pool-1)先执行0、1两个任务,然后将2、3两个任务添加到队列中,由于队列满了,所以又创建了一个非核心线程(demo-pool-2)处理任务4,等两个核心线程执行结束后又执行任务2和3。