|
| 1 | +package io.baishi.common.thread.threadpool; |
| 2 | + |
| 3 | +import io.baishi.common.thread.threadpool.dynamic.DynamicThreadPoolExecutor; |
| 4 | + |
| 5 | +import java.util.concurrent.RejectedExecutionHandler; |
| 6 | +import java.util.concurrent.ThreadFactory; |
| 7 | +import java.util.concurrent.TimeUnit; |
| 8 | + |
| 9 | +/** |
| 10 | + * 处理IO密集的线程池 |
| 11 | + * <p> |
| 12 | + * 最佳线程数 = CPU核数 * [ 1 +(I/O 耗时 / CPU 耗时)] |
| 13 | + * |
| 14 | + * @author baishi |
| 15 | + * @date 2022/1/17 14:50 |
| 16 | + */ |
| 17 | +public class IoThreadPoolBuilder extends AbstractThreadPoolBuilder { |
| 18 | + |
| 19 | + /** |
| 20 | + * 计算核心线程数量 |
| 21 | + * |
| 22 | + * @param ioTime |
| 23 | + * @param cpuTime |
| 24 | + * @return |
| 25 | + */ |
| 26 | + public int getCorePoolSize(int ioTime, int cpuTime) { |
| 27 | + return CPU_COUNT + (1 + (ioTime / cpuTime)); |
| 28 | + } |
| 29 | + |
| 30 | + public IoThreadPoolBuilder setThreadFactory(ThreadFactory threadFactory) { |
| 31 | + this.threadFactory = threadFactory; |
| 32 | + return this; |
| 33 | + } |
| 34 | + |
| 35 | + public IoThreadPoolBuilder setRejectedExecutionHandler(RejectedExecutionHandler rejectedExecutionHandler) { |
| 36 | + this.rejectedExecutionHandler = rejectedExecutionHandler; |
| 37 | + return this; |
| 38 | + } |
| 39 | + |
| 40 | + public IoThreadPoolBuilder setQueueSize(int queueSize) { |
| 41 | + this.queueSize = queueSize; |
| 42 | + return this; |
| 43 | + } |
| 44 | + |
| 45 | + public IoThreadPoolBuilder setMaximumPoolSize(int maximumPoolSize) { |
| 46 | + this.maximumPoolSize = maximumPoolSize; |
| 47 | + return this; |
| 48 | + } |
| 49 | + |
| 50 | + public IoThreadPoolBuilder setKeepAliveTimeMilliSeconds(int keepAliveTimeMilliSeconds) { |
| 51 | + this.keepAliveTimeMilliSeconds = keepAliveTimeMilliSeconds; |
| 52 | + return this; |
| 53 | + } |
| 54 | + |
| 55 | + public IoThreadPoolBuilder setDaemon(boolean daemon) { |
| 56 | + this.daemon = daemon; |
| 57 | + return this; |
| 58 | + } |
| 59 | + |
| 60 | + public IoThreadPoolBuilder setThreadNamePrefix(String threadNamePrefix) { |
| 61 | + this.threadNamePrefix = threadNamePrefix; |
| 62 | + return this; |
| 63 | + } |
| 64 | + |
| 65 | + public DynamicThreadPoolExecutor builder(int ioTime, int cpuTime) { |
| 66 | + |
| 67 | + threadFactory = ThreadPoolUtils.createThreadFactory(this.threadNamePrefix, this.daemon); |
| 68 | + |
| 69 | + return new DynamicThreadPoolExecutor( |
| 70 | + getCorePoolSize(ioTime, cpuTime), |
| 71 | + getMaximumPoolSize(getCorePoolSize(ioTime, cpuTime)), |
| 72 | + keepAliveTimeMilliSeconds, |
| 73 | + TimeUnit.MILLISECONDS, |
| 74 | + getBlockingQueue(), |
| 75 | + threadFactory, |
| 76 | + getRejectedExecutionHandler()); |
| 77 | + } |
| 78 | +} |
0 commit comments