|
| 1 | +package edu.maskleo.module1; |
| 2 | + |
| 3 | +import java.util.concurrent.BlockingDeque; |
| 4 | +import java.util.concurrent.LinkedBlockingDeque; |
| 5 | + |
| 6 | +public class ThreadPool { |
| 7 | + |
| 8 | + private static BlockingDeque<Runnable> deque = new LinkedBlockingDeque<>(); |
| 9 | + private int maxIdle = -1; |
| 10 | + private int minIdle = -1; |
| 11 | + private int maxActive = -1; |
| 12 | + private int maxWait = -1; |
| 13 | + |
| 14 | + private ThreadPool() { |
| 15 | + } |
| 16 | + |
| 17 | + /** |
| 18 | + * 计算该线程是否需要销毁 |
| 19 | + * |
| 20 | + * @return |
| 21 | + */ |
| 22 | + private static boolean keepOn() { |
| 23 | + return true; |
| 24 | + } |
| 25 | + |
| 26 | + /** |
| 27 | + * 线程加入线程队列 |
| 28 | + * |
| 29 | + * @param t |
| 30 | + */ |
| 31 | + private static void put(Runnable t) { |
| 32 | + try { |
| 33 | + deque.put(t); |
| 34 | + } catch (Exception e) { |
| 35 | + ; |
| 36 | + } |
| 37 | + |
| 38 | + } |
| 39 | + |
| 40 | + public static ThreadPool build() { |
| 41 | + return new ThreadPool(); |
| 42 | + } |
| 43 | + |
| 44 | + public int getMaxIdle() { |
| 45 | + return maxIdle; |
| 46 | + } |
| 47 | + |
| 48 | + public ThreadPool setMaxIdle(int maxIdle) { |
| 49 | + this.maxIdle = maxIdle; |
| 50 | + return this; |
| 51 | + } |
| 52 | + |
| 53 | + public int getMinIdle() { |
| 54 | + return minIdle; |
| 55 | + } |
| 56 | + |
| 57 | + public ThreadPool setMinIdle(int minIdle) { |
| 58 | + this.minIdle = minIdle; |
| 59 | + return this; |
| 60 | + } |
| 61 | + |
| 62 | + public int getMaxActive() { |
| 63 | + return maxActive; |
| 64 | + } |
| 65 | + |
| 66 | + public ThreadPool setMaxActive(int maxActive) { |
| 67 | + this.maxActive = maxActive; |
| 68 | + return this; |
| 69 | + } |
| 70 | + |
| 71 | + public int getMaxWait() { |
| 72 | + return maxWait; |
| 73 | + } |
| 74 | + |
| 75 | + public ThreadPool setMaxWait(int maxWait) { |
| 76 | + this.maxWait = maxWait; |
| 77 | + return this; |
| 78 | + } |
| 79 | + |
| 80 | + private static class InnerThread implements Runnable { |
| 81 | + |
| 82 | + private InnerThread() { |
| 83 | + } |
| 84 | + |
| 85 | + @Override |
| 86 | + public void run() { |
| 87 | + while (keepOn()) { |
| 88 | + try { |
| 89 | + Runnable thread = deque.take(); |
| 90 | + thread.run(); |
| 91 | + put(this); |
| 92 | + } catch (Exception e) { |
| 93 | + ; |
| 94 | + } |
| 95 | + |
| 96 | + } |
| 97 | + } |
| 98 | + } |
| 99 | +} |
0 commit comments