07-线程池

7.1 自定义线程池

![image.png](https://img-blog.csdnimg.cn/img_convert/2e68c2b0a1b4f3c2c734c9dbd20d97e7.png#averageHue=#fdfcef&clientId=uf663d050-93f7-4&errorMessage=unknown error&from=paste&height=407&id=u1b98b89f&name=image.png&originHeight=509&originWidth=1036&originalType=binary&ratio=1&rotation=0&showTitle=false&size=40952&status=error&style=none&taskId=u33bbd435-2283-41d0-917b-4de8f70e3fa&title=&width=828.8)
第一步:有界线程安全的阻塞队列

/**
* 有界阻塞队列
*/
@Slf4j(topic = "c.BlockQueue")
class BlockQueue<T> {
	
	/**
	* 任务队列
	*/
	private final Deque<T> queue = new ArrayDeque<>();
	/**
	* 锁
	*/
	private final ReentrantLock lock = new ReentrantLock();
	/**
	* 生产者条件变量
	*/
	private final Condition fullWaitSet = lock.newCondition();
	/**
	* 消费者条件变量
	*/
	private final Condition emptyWaitSet = lock.newCondition();
	
	/**
	* 容量
	*/
	private final int capcity;
	
	public BlockQueue(int capcity) {
		this.capcity = capcity;
	}
	
	/**
	* 线程安全的阻塞获取
	*
	* @return
	*/
	public T take() {
		lock.lock();
		try {
			while (queue.isEmpty()) {
				try {
					// 消费不到时  等待生产者添加后唤醒
					emptyWaitSet.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			T t = queue.removeFirst();
			// 移除一个后 不在是满的队列 需要唤醒等待的生产者线程
			fullWaitSet.signal();
			return t;
		} finally {
			lock.unlock();
		}
	}
	
	/**
	* 线程安全的阻塞获取  带超时时间
	*
	* @return
	*/
	public T take(long timeout, TimeUnit timeUnit) {
		lock.lock();
		try {
			long waitTime = timeUnit.toNanos(timeout);
			while (queue.isEmpty()) {
				try {
					if (waitTime <= 0) {
						// 等过了超时时间
						return null;
					}
					// 消费不到时  等待生产者添加后唤醒
					waitTime = emptyWaitSet.awaitNanos(waitTime);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			T t = queue.removeFirst();
			// 移除一个后 不在是满的队列 需要唤醒等待的生产者线程
			fullWaitSet.signal();
			return t;
		} finally {
			lock.unlock();
		}
	}
	
	/**
	* 线程安全的添加任务
	*
	* @param task
	*/
	public void put(T task) {
		lock.lock();
		try {
			while (queue.size() == capcity) {
				try {
					log.debug("等待加入任务队列{}", task);
					// 阻塞  等待消费者消费后唤醒
					/**
					* 注意wait是Object的方法  需要配合synchronized使用
					* await为Condition方法
					*/
					fullWaitSet.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			queue.addLast(task);
			log.debug("成功加入任务队列,{}", task);
			// 唤醒消费者等待
			emptyWaitSet.signal();
		} finally {
			lock.unlock();
		}
	}
	
	/**
	* 线程安全的添加任务  带超时时间
	*
	* @param task
	* @param timeout
	* @param timeUnit
	*/
	public boolean put(T task, long timeout, TimeUnit timeUnit) {
		lock.lock();
		try {
			long waitTime = timeUnit.toNanos(timeout);
			while (queue.size() == capcity) {
				try {
					if (waitTime <= 0) {
						return false;
					}
					log.debug("等待加入任务队列{}...", task);
					// 阻塞  等待消费者消费后唤醒
					waitTime = fullWaitSet.awaitNanos(waitTime);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			queue.addLast(task);
			log.debug("成功加入任务队列,{}", task);
			// 唤醒消费者等待
			emptyWaitSet.signal();
			return true;
		} finally {
			lock.unlock();
		}
	}
	
	/**
	* 获取队列大小
	*
	* @return
	*/
	public int size() {
		lock.lock();
		try {
			return queue.size();
		} finally {
			lock.unlock();
		}
	}
	
	/**
	* 添加入队列 - 带拒绝策略的
	*
	* @param rejectPolicy
	* @param task
	*/
	public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
		lock.lock();
		try {
			if (queue.size() == capcity) {
				// 不再等待  直接执行拒绝策略
				rejectPolicy.reject(this, task);
			} else {
				queue.addLast(task);
				log.debug("加入任务队列{}", task);
				// 唤醒消费者等待
				emptyWaitSet.signal();
			}
		} finally {
			lock.unlock();
		}
	}
	
}

第二步:队列满了之后的拒绝策略

/**
 * 拒绝策略
 *
 * @param <T>
 */
@FunctionalInterface
interface RejectPolicy<T> {

    void reject(BlockQueue<T> queue, T task);

}

第三步:自定义线程池以及工作线程

/**
 * 线程池 简陋版
 * 没有救急线程和相关的救急线程 超时时间等
 */
@Slf4j(topic = "c.ThreadPool")
class ThreadPool {
    /**
     * 任务队列
     */
    private BlockQueue<Runnable> taskQueue;
    /**
     * 工作线程集合
     */
    private final Set<Worker> workers = new HashSet<>();
    /**
     * 核心线程
     */
    private int coreSize;
    /**
     * 从队列中获取任务的超时时间
     */
    private long timeout;
    private TimeUnit timeUnit;
    /**
     * 拒绝策略
     */
    private RejectPolicy<Runnable> rejectPolicy;

    public ThreadPool(int coreSize, long timeout, TimeUnit timeUnit, int queueCapcity, RejectPolicy<Runnable> rejectPolicy) {
        this.coreSize = coreSize;
        this.timeout = timeout;
        this.timeUnit = timeUnit;
        this.taskQueue = new BlockQueue<>(queueCapcity);
        this.rejectPolicy = rejectPolicy;
    }

    /**
     * 执行任务
     *
     * @param task
     */
    public void execute(Runnable task) {
        // 当任务没有超过核心线程数时  直接交给worker对象执行
        // 当任务超过核心线程数时  加入任务队列暂存
        synchronized (workers) {
            if (workers.size() < coreSize) {
                Worker worker = new Worker(task);
                log.debug("新增worker{},任务{}", worker, task);
                workers.add(worker);
                worker.start();
            } else {
                // 存入任务队列 阻塞
                //taskQueue.put(task);
                // 带策略的存入任务队列
                /**
                 * 1. 死等
                 * 2. 带超时的等待
                 * 3. 让调用者放弃任务执行
                 * 4. 让调用者抛出异常
                 * 5. 让调用者自己执行任务
                 */
                taskQueue.tryPut(rejectPolicy, task);
            }
        }
    }

    class Worker extends Thread {

        private Runnable task;

        public Worker(Runnable target) {
            this.task = target;
        }

        @Override
        public void run() {
            /**
             * 1. 当task不为空时 执行任务
             * 2. 当task执行完毕 再接着从任务队列获取任务并执行
             */
            while (Objects.nonNull(task) || Objects.nonNull(task = taskQueue.take(timeout, timeUnit))) {
                try {
                    log.debug("正在执行{}", task);
                    task.run();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    task = null;
                }
            }
            // 没有任务且队列中也在超时时间内没有获取到任务
            synchronized (workers) {
                log.debug("worker被移除{}", this);
                workers.remove(this);
            }
        }
    }

}

第四步:测试

@Slf4j(topic = "c.TestMyThreadPool")
public class TestMyThreadPool {

    public static void main(String[] args) {
        ThreadPool threadPool = new ThreadPool(1, 1000, TimeUnit.MILLISECONDS, 1, (queue, task) -> {
            //1. 死等
            //queue.put(task);
            //2. 带超时等待
            //queue.put(task, 1500, TimeUnit.MILLISECONDS);
            //3. 让调用者放弃
            //log.debug("放弃任务:{}", task);
            //4. 调用者抛出异常 不影响之前线程  会影响调用者后面的任务加入
            //throw new RuntimeException("任务执行失败:" + task);
            //5. 由调用者线程调用
            task.run();
        });

        for (int i = 0; i < 4; i++) {
            final int j = i;
            threadPool.execute(() -> {
                log.debug("execute线程{}", j);
                Sleeper.sleep(3);
            });
        }
    }

}

7.2 ThreadPoolExecutor

![image.png](https://img-blog.csdnimg.cn/img_convert/998be21606a9e097d1cd2f616b851633.png#averageHue=#fcfcf7&clientId=u5e2e8211-22b4-4&errorMessage=unknown error&from=paste&height=331&id=u3714067a&name=image.png&originHeight=414&originWidth=1017&originalType=binary&ratio=1&rotation=0&showTitle=false&size=68045&status=error&style=none&taskId=ube447ae6-f256-4ded-bc58-1e3399a92b9&title=&width=813.6)

7.2.1 线程池状态

ThreadPoolExecutor 使用 int 的高 3 位来表示线程池状态,低 29 位表示线程数量
![image.png](https://img-blog.csdnimg.cn/img_convert/613e683558fbdb576679610ed2fd1c6d.png#averageHue=#f7f6f6&clientId=u5e2e8211-22b4-4&errorMessage=unknown error&from=paste&height=399&id=u2ab68283&name=image.png&originHeight=499&originWidth=1086&originalType=binary&ratio=1&rotation=0&showTitle=false&size=103512&status=error&style=none&taskId=u42d47583-7950-4632-a840-bf22a708778&title=&width=868.8)
从数字上比较,TERMINATED > TIDYING > STOP > SHUTDOWN > RUNNING
这些信息存储在一个原子变量 ctl 中,目的是将线程池状态与线程个数合二为一,这样就可以用一次 cas 原子操作
进行赋值

// c 为旧值, ctlOf 返回结果为新值
ctl.compareAndSet(c, ctlOf(targetState, workerCountOf(c))));
// rs 为高 3 位代表线程池状态, wc 为低 29 位代表线程个数,ctl 是合并它们
private static int ctlOf(int rs, int wc) { return rs | wc; }

7.2.2 构造方法

public ThreadPoolExecutor(int corePoolSize,
						  int maximumPoolSize,
						  long keepAliveTime,
						  TimeUnit unit,
						  BlockingQueue<Runnable> workQueue,
						  ThreadFactory threadFactory,
						  RejectedExecutionHandler handler)
  • corePoolSize 核心线程数目 (最多保留的线程数)
  • maximumPoolSize 最大线程数目
  • maximumPoolSize - corePoolSize 救急线程数
  • keepAliveTime 生存时间 - 针对救急线程
  • unit 时间单位 - 针对救急线程
  • workQueue 阻塞队列
  • threadFactory 线程工厂 - 可以为线程创建时起个好名字
  • handler 拒绝策略

工作方式:
![image.png](https://img-blog.csdnimg.cn/img_convert/9cf5c8c212211bbae68ce1d6a40e0c5b.png#averageHue=#fdfcef&clientId=u5e2e8211-22b4-4&errorMessage=unknown error&from=paste&height=609&id=u30788620&name=image.png&originHeight=761&originWidth=499&originalType=binary&ratio=1&rotation=0&showTitle=false&size=52633&status=error&style=none&taskId=u1036e395-6755-4de8-b9b9-5de8fc3af9b&title=&width=399.2)

  • 线程池中刚开始没有线程,当一个任务提交给线程池后,线程池会创建一个新线程来执行任务。
  • 当线程数达到 corePoolSize 并没有线程空闲,这时再加入任务,新加的任务会被加入workQueue 队列排队,直到有空闲的线程。
  • 如果队列选择了有界队列,那么任务超过了队列大小时,会创建 maximumPoolSize - corePoolSize 数目的线程来救急。
  • 如果线程到达 maximumPoolSize 仍然有新任务这时会执行拒绝策略。拒绝策略 jdk 提供了 4 种实现,其它著名框架也提供了实现
    • AbortPolicy 让调用者抛出 RejectedExecutionException 异常,这是默认策略
    • CallerRunsPolicy 让调用者运行任务
    • DiscardPolicy 放弃本次任务
    • DiscardOldestPolicy 放弃队列中最早的任务,本任务取而代之
    • Dubbo 的实现,在抛出 RejectedExecutionException 异常之前会记录日志,并 dump 线程栈信息,方便定位问题
    • Netty 的实现,是创建一个新线程来执行任务
    • ActiveMQ 的实现,带超时等待(60s)尝试放入队列,类似我们之前自定义的拒绝策略
    • PinPoint 的实现,它使用了一个拒绝策略链,会逐一尝试策略链中每种拒绝策略
  • 当高峰过去后,超过corePoolSize 的救急线程如果一段时间没有任务做,需要结束节省资源,这个时间由 keepAliveTime 和 unit 来控制。

![image.png](https://img-blog.csdnimg.cn/img_convert/3fc93564fc7a93b5cd291715aa72a8ce.png#averageHue=#fcfbf6&clientId=u5e2e8211-22b4-4&errorMessage=unknown error&from=paste&height=163&id=u7a211274&name=image.png&originHeight=204&originWidth=1063&originalType=binary&ratio=1&rotation=0&showTitle=false&size=44350&status=error&style=none&taskId=u9becbb8c-92c7-4d91-9b72-ec184cddeec&title=&width=850.4)
根据这个构造方法,JDK Executors 类中提供了众多工厂方法来创建各种用途的线程池

7.2.3 newFixedThreadPool

public static ExecutorService newFixedThreadPool(int nThreads) {
	return new ThreadPoolExecutor(nThreads, nThreads,
								  0L, TimeUnit.MILLISECONDS,
								  new LinkedBlockingQueue<Runnable>());
}

特点

  • 核心线程数 == 最大线程数(没有救急线程被创建),因此也无需超时时间
  • 阻塞队列是无界的,可以放任意数量的任务
  • 适用于任务量已知,相对耗时的任务

7.2.4 newCachedThreadPool

public static ExecutorService newCachedThreadPool() {
	return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
								  60L, TimeUnit.SECONDS,
								  new SynchronousQueue<Runnable>());
}

特点

  • 核心线程数是 0, 最大线程数是 Integer.MAX_VALUE,救急线程的空闲生存时间是 60s,意味着全部都是救急线程(60s 后可以回收)
  • 救急线程可以无限创建
  • 队列采用了 SynchronousQueue 实现特点是,它没有容量,没有线程来取是放不进去的(一手交钱、一手交货)
  • 整个线程池表现为线程数会根据任务量不断增长,没有上限,当任务执行完毕,空闲 1分钟后释放线程。 适合任务数比较密集,但每个任务执行时间较短的情况
@Slf4j(topic = "c.TestSynchronousQueue")
public class TestSynchronousQueue {

    public static void main(String[] args) {
        SynchronousQueue<Integer> intQueue = new SynchronousQueue<>();

        new Thread(() -> {
            try {
                log.debug("put 1 into queue");
                // SynchronousQueue队列put必须要有其他线程取才能put成功
                // 这里会阻塞住 等到有线程来取
                intQueue.put(1);
                log.debug("put 1 success");

                log.debug("put 2 into queue");
                intQueue.put(2);
                log.debug("put 2 success");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t1").start();
        //停止2秒 t1线程put等待
        Sleeper.sleep(2);

        new Thread(() -> {
            try {
                log.debug("taking");
                Integer result = intQueue.take();
                log.debug("taked result:{}", result);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t2").start();
        Sleeper.sleep(2);

        new Thread(() -> {
            try {
                log.debug("taking");
                Integer result = intQueue.take();
                log.debug("taked result:{}", result);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t3").start();


    }


}

22:03:45.183 c.TestSynchronousQueue [t1] - put 1 into queue
22:03:47.184 c.TestSynchronousQueue [t2] - taking
22:03:47.184 c.TestSynchronousQueue [t1] - put 1 success
22:03:47.184 c.TestSynchronousQueue [t1] - put 2 into queue
22:03:47.184 c.TestSynchronousQueue [t2] - taked result:1
22:03:49.185 c.TestSynchronousQueue [t3] - taking
22:03:49.185 c.TestSynchronousQueue [t3] - taked result:2
22:03:49.185 c.TestSynchronousQueue [t1] - put 2 success

7.2.5 newSingleThreadExecutor

public static ExecutorService newSingleThreadExecutor() {
	return new FinalizableDelegatedExecutorService
		(new ThreadPoolExecutor(1, 1,
								0L, TimeUnit.MILLISECONDS,
								new LinkedBlockingQueue<Runnable>()));
}

使用场景:
希望多个任务排队执行。线程数固定为 1,任务数多于 1 时,会放入无界队列排队。任务执行完毕,这唯一的线程也不会被释放。
区别:

  • 自己创建一个单线程串行执行任务,如果任务执行失败而终止那么没有任何补救措施,而线程池还会新建一个线程,保证池的正常工作
  • Executors.newSingleThreadExecutor() 线程个数始终为1,不能修改
    • FinalizableDelegatedExecutorService 应用的是装饰器模式,只对外暴露了 ExecutorService 接口,因此不能调用 ThreadPoolExecutor 中特有的方法
  • Executors.newFixedThreadPool(1) 初始时为1,以后还可以修改
    • 对外暴露的是 ThreadPoolExecutor 对象,可以强转后调用 setCorePoolSize 等方法进行修改

7.2.6 提交任务

// 执行任务
void execute(Runnable command);

// 提交任务 task,用返回值 Future 获得任务执行结果
<T> Future<T> submit(Callable<T> task);

// 提交 tasks 中所有任务
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException;

// 提交 tasks 中所有任务,带超时时间
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException;

// 提交 tasks 中所有任务,哪个任务先成功执行完毕,返回此任务执行结果,其它任务取消
<T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException;

// 提交 tasks 中所有任务,哪个任务先成功执行完毕,返回此任务执行结果,其它任务取消,带超时时间
<T> T invokeAny(Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;

7.2.7 关闭线程池

shutdown

/*
线程池状态变为 SHUTDOWN
- 不会接收新任务
- 但已提交任务会执行完
- 此方法不会阻塞调用线程的执行
*/
void shutdown();

public void shutdown() {
	final ReentrantLock mainLock = this.mainLock;
	mainLock.lock();
	try {
		checkShutdownAccess();
		// 修改线程池状态
		advanceRunState(SHUTDOWN);
		// 仅会打断空闲线程
		interruptIdleWorkers();
		onShutdown(); // 扩展点 ScheduledThreadPoolExecutor
	} finally {
		mainLock.unlock();
	}
	// 尝试终结(没有运行的线程可以立刻终结,如果还有运行的线程也不会等)
	tryTerminate();
}

shutdownNow

/*
线程池状态变为 STOP
- 不会接收新任务
- 会将队列中的任务返回
- 并用 interrupt 的方式中断正在执行的任务
*/
List<Runnable> shutdownNow();

public List<Runnable> shutdownNow() {
	List<Runnable> tasks;
	final ReentrantLock mainLock = this.mainLock;
	mainLock.lock();
	try {
		checkShutdownAccess();
		// 修改线程池状态
		advanceRunState(STOP);
		// 打断所有线程
		interruptWorkers();
		// 获取队列中剩余任务
		tasks = drainQueue();
	} finally {
		mainLock.unlock();
	}
	// 尝试终结
	tryTerminate();
	return tasks; 
}

其他方法

// 不再 RUNNING 状态的线程池,此方法就返回 true
boolean isShutdown();
// 线程池状态是否是 TERMINATED
boolean isTerminated();
// 调用 shutdown 后,由于调用线程并不会等待所有任务运行结束,因此如果它想在线程池 TERMINATED 后做些事情,可以利用此方法等待
boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException;

7.2.8 任务调度线程池

在『任务调度线程池』功能加入之前,可以使用 java.util.Timer 来实现定时功能,Timer 的优点在于简单易用,但由于所有任务都是由同一个线程来调度,因此所有任务都是串行执行的,同一时间只能有一个任务在执行,前一个任务的延迟或异常都将会影响到之后的任务。

@Slf4j(topic = "c.TestTimer")
public class TestTimer {

    public static void main(String[] args) {
        Timer timer = new Timer();
        TimerTask task1 = new TimerTask() {
            @Override
            public void run() {
                log.debug("task1");
                Sleeper.sleep(2);
            }
        };

        TimerTask task2 = new TimerTask() {
            @Override
            public void run() {
                log.debug("task2");
            }
        };
        log.debug("start...");
        // 使用 timer 添加两个任务,希望它们都在 1s 后执行
        // 但由于 timer 内只有一个线程来顺序执行队列中的任务,因此『任务1』的延时,影响了『任务2』的执行
        timer.schedule(task1, 1000);
        timer.schedule(task2, 1000);
    }
}

输出:
20:58:10.925 c.TestTimer [main] - start...
20:58:11.936 c.TestTimer [Timer-0] - task1
20:58:13.947 c.TestTimer [Timer-0] - task2

使用 ScheduledExecutorService 改写

@Slf4j(topic = "c.TestTimer")
public class TestTimer {
	
	public static void main(String[] args) {
		ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(2);
		// 添加两个任务  让它们都在1s后执行
		scheduledThreadPool.schedule(()->{
			log.debug("task1");
			Sleeper.sleep(2);
		}, 1000, TimeUnit.MILLISECONDS);
		
		scheduledThreadPool.schedule(()->{
			log.debug("task2");
		}, 1000, TimeUnit.MILLISECONDS);
		
	}
}

输出
21:03:49.248 c.TestTimer [pool-1-thread-2] - task2
21:03:49.248 c.TestTimer [pool-1-thread-1] - task1

scheduleAtFixedRate 例子:

@Slf4j(topic = "c.TestTimer")
public class TestTimer {

    public static void main(String[] args) {
        log.debug("start...");
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);
        scheduledThreadPool.scheduleAtFixedRate(()->{
            log.debug("running...");
        }, 1, 1, TimeUnit.SECONDS);

    }
}

输出(延时1s后每个1秒执行一次)
21:07:52.298 c.TestTimer [main] - start...
21:07:53.348 c.TestTimer [pool-1-thread-1] - running...
21:07:54.346 c.TestTimer [pool-1-thread-1] - running...
21:07:55.359 c.TestTimer [pool-1-thread-1] - running...
21:07:56.355 c.TestTimer [pool-1-thread-1] - running...
21:07:57.354 c.TestTimer [pool-1-thread-1] - running...

scheduleAtFixedRate 例子(任务执行时间超过了间隔时间):

@Slf4j(topic = "c.TestTimer")
public class TestTimer {

    public static void main(String[] args) {
        log.debug("start...");
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);
        scheduledThreadPool.scheduleAtFixedRate(()->{
            log.debug("running...");
            Sleeper.sleep(2);
        }, 1, 1, TimeUnit.SECONDS);

    }
}

输出(一开始,延时 1s,接下来,由于任务执行时间 > 间隔时间,间隔被『撑』到了 2s)
21:10:12.973 c.TestTimer [main] - start...
21:10:14.021 c.TestTimer [pool-1-thread-1] - running...
21:10:16.024 c.TestTimer [pool-1-thread-1] - running...
21:10:18.037 c.TestTimer [pool-1-thread-1] - running...
21:10:20.046 c.TestTimer [pool-1-thread-1] - running...
21:10:22.054 c.TestTimer [pool-1-thread-1] - running...

scheduleWithFixedDelay 例子:

@Slf4j(topic = "c.TestTimer")
public class TestTimer {

    public static void main(String[] args) {
        //testTimer();
        //testSchedulePool();
        //testScheduleFixRate1();
        //testScheduleFixRate2();

        log.debug("start...");
        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);
        scheduledThreadPool.scheduleWithFixedDelay(()->{
            log.debug("running...");
            Sleeper.sleep(2);
        }, 1, 1, TimeUnit.SECONDS);

    }
}

输出(一开始,延时 1s,scheduleWithFixedDelay 的间隔是 上一个任务结束 <-> 延时 <-> 下一个任务开始 所以间隔都是 3s)
21:12:56.787 c.TestTimer [main] - start...
21:12:57.845 c.TestTimer [pool-1-thread-1] - running...
21:13:00.859 c.TestTimer [pool-1-thread-1] - running...
21:13:03.870 c.TestTimer [pool-1-thread-1] - running...
21:13:06.891 c.TestTimer [pool-1-thread-1] - running...

:::info
整个线程池表现为:线程数固定,任务数多于线程数时,会放入无界队列排队。任务执行完毕,这些线
程也不会被释放。用来执行延迟或反复执行的任务。
:::

7.2.9 正确处理执行任务异常

方法1:主动捉异常

@Slf4j(topic = "c.TestThreadPoolException")
public class TestThreadPoolException {

    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(1);
        pool.submit(() -> {
            try {
                log.debug("task1");
                int i = 1 / 0;
            } catch (Exception e) {
                log.error("error:", e);
            }
        });
    }

}

方法2:使用 Future

@Slf4j(topic = "c.TestThreadPoolException")
public class TestThreadPoolException {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(1);
        Future<Boolean> f = pool.submit(() -> {
            log.debug("task1");
            int i = 1 / 0;
            return true;
        });
        log.debug("result:{}", f.get());
    }
}

7.2.10 Tomcat线程池

Tomcat 在哪里用到了线程池呢

  • LimitLatch 用来限流,可以控制最大连接个数,类似 J.U.C 中的 Semaphore 后面再讲
  • Acceptor 只负责【接收新的 socket 连接】
  • Poller 只负责监听 socket channel 是否有【可读的 I/O 事件】
  • 一旦可读,封装一个任务对象(socketProcessor),提交给 Executor 线程池处理
  • Executor 线程池中的工作线程最终负责【处理请求】

Tomcat 线程池扩展了 ThreadPoolExecutor,行为稍有不同

  • 如果总线程数达到 maximumPoolSize
    • 这时不会立刻抛 RejectedExecutionException 异常
    • 而是再次尝试将任务放入队列,如果还失败,才抛出 RejectedExecutionException 异常
public void execute(Runnable command, long timeout, TimeUnit unit) {
	submittedCount.incrementAndGet();
	try {
		super.execute(command);
	} catch (RejectedExecutionException rx) {
		if (super.getQueue() instanceof TaskQueue) {
			final TaskQueue queue = (TaskQueue)super.getQueue();
			try {
				if (!queue.force(command, timeout, unit)) {
					submittedCount.decrementAndGet();
					throw new RejectedExecutionException("Queue capacity is full.");
				}
			} catch (InterruptedException x) {
				submittedCount.decrementAndGet();
				Thread.interrupted();
				throw new RejectedExecutionException(x);
			}
		} else {
			submittedCount.decrementAndGet();
			throw rx;
		}
	}
}

public boolean force(Runnable o, long timeout, TimeUnit unit) throws InterruptedException {
	if ( parent.isShutdown() ) 
		throw new RejectedExecutionException(
		"Executor not running, can't force a command into the queue"
	);
	return super.offer(o,timeout,unit); //forces the item onto the queue, to be used if the task is rejected
}

Connector 配置
![image.png](https://img-blog.csdnimg.cn/img_convert/2bbd02e324651ec8745b7729a1f3b738.png#averageHue=#f7f6f6&clientId=u8d5fc47c-5941-4&errorMessage=unknown error&from=paste&height=280&id=u2e208beb&name=image.png&originHeight=350&originWidth=1050&originalType=binary&ratio=1&rotation=0&showTitle=false&size=78931&status=error&style=none&taskId=u5ed163a6-3639-4ed5-904e-e20f507ff23&title=&width=840)
Executor 线程配置
![image.png](https://img-blog.csdnimg.cn/img_convert/b4f956f612bb379e88fdde55a2844255.png#averageHue=#f7f6f5&clientId=u8d5fc47c-5941-4&errorMessage=unknown error&from=paste&height=368&id=ub6abfc64&name=image.png&originHeight=460&originWidth=1070&originalType=binary&ratio=1&rotation=0&showTitle=false&size=98768&status=error&style=none&taskId=u2752e831-f7e8-46fb-ab81-6f872e05457&title=&width=856)
![image.png](https://img-blog.csdnimg.cn/img_convert/13c871e4ee4e077e880ad6b7092356c8.png#averageHue=#fcfcfc&clientId=u8d5fc47c-5941-4&errorMessage=unknown error&from=paste&height=233&id=u02f8ddfe&name=image.png&originHeight=291&originWidth=1023&originalType=binary&ratio=1&rotation=0&showTitle=false&size=47620&status=error&style=none&taskId=u74360f5b-ddba-46fd-833c-5dac502f5d6&title=&width=818.4)

7.3 异步模式之工作线程

7.3.1 定义

让有限的工作线程(Worker Thread)来轮流异步处理无限多的任务。也可以将其归类为分工模式,它的典型实现就是线程池,也体现了经典设计模式中的享元模式。
例如,海底捞的服务员(线程),轮流处理每位客人的点餐(任务),如果为每位客人都配一名专属的服务员,那
么成本就太高了(对比另一种多线程设计模式:Thread-Per-Message)
注意,不同任务类型应该使用不同的线程池,这样能够避免饥饿,并能提升效率
例如,如果一个餐馆的工人既要招呼客人(任务类型A),又要到后厨做菜(任务类型B)显然效率不咋地,分成
服务员(线程池A)与厨师(线程池B)更为合理,当然你能想到更细致的分工

7.3.2 饥饿

固定大小线程池会有饥饿现象

  • 两个工人是同一个线程池中的两个线程
  • 他们要做的事情是:为客人点餐和到后厨做菜,这是两个阶段的工作
    • 客人点餐:必须先点完餐,等菜做好,上菜,在此期间处理点餐的工人必须等待
    • 后厨做菜:没啥说的,做就是了
  • 比如工人A 处理了点餐任务,接下来它要等着 工人B 把菜做好,然后上菜,他俩也配合的蛮好
  • 但现在同时来了两个客人,这个时候工人A 和工人B 都去处理点餐了,这时没人做饭了,饥饿
@Slf4j(topic = "c.TestStarvation")
public class TestStarvation {

    private static final List<String> MENU = Arrays.asList("地三鲜", "宫保鸡丁", "辣子鸡丁", "烤鸡翅");
    private static final Random RANDOM = new Random();

    private static String cooking() {
        return MENU.get(RANDOM.nextInt(MENU.size()));
    }

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        /*点餐之后上菜 */
        executorService.execute(() -> {
            log.debug("处理点餐...");
            Future<String> future = executorService.submit(() -> {
                log.debug("做菜");
                return cooking();
            });
            try {
                log.debug("上菜:{}", future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }

        });

        /*executorService.execute(() -> {
            log.debug("处理点餐...");
            Future<String> future = executorService.submit(() -> {
                log.debug("做菜");
                return cooking();
            });
            try {
                log.debug("上菜:{}", future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }

        });*/

        /*线程池处理两个点餐任务  导致做菜任务阻塞等待。。*/
        
    }

}

输出

19:14:01.974 c.TestStarvation [pool-1-thread-1] - 处理点餐...
19:14:01.990 c.TestStarvation [pool-1-thread-2] - 做菜
19:14:01.990 c.TestStarvation [pool-1-thread-1] - 上菜:宫保鸡丁

当注释取消后,可能的输出

19:12:36.077 c.TestStarvation [pool-1-thread-1] - 处理点餐...
19:12:36.077 c.TestStarvation [pool-1-thread-2] - 处理点餐...

解决方法可以增加线程池的大小,不过不是根本解决方案,还是前面提到的,不同的任务类型,采用不同的线程池,例如:

@Slf4j(topic = "c.TestStarvation")
public class TestStarvation {

    private static final List<String> MENU = Arrays.asList("地三鲜", "宫保鸡丁", "辣子鸡丁", "烤鸡翅");
    private static final Random RANDOM = new Random();

    private static String cooking() {
        return MENU.get(RANDOM.nextInt(MENU.size()));
    }

    public static void main(String[] args) {
        ExecutorService waiterService = Executors.newFixedThreadPool(2);
        ExecutorService cookerService = Executors.newFixedThreadPool(2);

        /*点餐之后上菜 */
        waiterService.execute(() -> {
            log.debug("处理点餐...");
            Future<String> future = cookerService.submit(() -> {
                log.debug("做菜");
                return cooking();
            });
            try {
                log.debug("上菜:{}", future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }

        });

        waiterService.execute(() -> {
            log.debug("处理点餐...");
            Future<String> future = cookerService.submit(() -> {
                log.debug("做菜");
                return cooking();
            });
            try {
                log.debug("上菜:{}", future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }

        });

    }

}

输出

19:15:50.354 c.TestStarvation [pool-1-thread-1] - 处理点餐...
19:15:50.354 c.TestStarvation [pool-1-thread-2] - 处理点餐...
19:15:50.370 c.TestStarvation [pool-2-thread-1] - 做菜
19:15:50.370 c.TestStarvation [pool-2-thread-2] - 做菜
19:15:50.370 c.TestStarvation [pool-1-thread-1] - 上菜:地三鲜
19:15:50.370 c.TestStarvation [pool-1-thread-2] - 上菜:宫保鸡丁

7.3.3 创建多少线程池合适

  • 过小会导致程序不能充分地利用系统资源、容易导致饥饿
  • 过大会导致更多的线程上下文切换,占用更多内存

CPU 密集型运算
通常采用** cpu 核数 + 1 **能够实现最优的 CPU 利用率,+1 是保证当线程由于页缺失故障(操作系统)或其它原因导致暂停时,额外的这个线程就能顶上去,保证 CPU 时钟周期不被浪费
I/O 密集型运算
CPU 不总是处于繁忙状态,例如,当你执行业务计算时,这时候会使用 CPU 资源,但当你执行 I/O 操作时、远程RPC 调用时,包括进行数据库操作时,这时候 CPU 就闲下来了,你可以利用多线程提高它的利用率。
经验公式如下

线程数 = 核数 * 期望 CPU 利用率 * 总时间(CPU计算时间+等待时间) / CPU 计算时间

例如 4 核 CPU 计算时间是 50% ,其它等待时间是 50%,期望 cpu 被 100% 利用,套用公式
4 * 100% * 100% / 50% = 8

例如 4 核 CPU 计算时间是 10% ,其它等待时间是 90%,期望 cpu 被 100% 利用,套用公式
4 * 100% * 100% / 10% = 40

7.4 应用之定时任务

如何让每周四 18:00:00 定时执行任务?

@Slf4j(topic = "c.TestScheduleTask")
public class TestScheduleTask {

    public static void main(String[] args) {
        // 1. 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        // 2. 获取周六时间 本周六或者下周六。。。
        LocalDateTime targetTime = now.withHour(21).withMinute(38).withSecond(0).withNano(0).with(DayOfWeek.SATURDAY);
        if (now.compareTo(targetTime) > 0) {
            //如果当前时间>本周周六  必须找到下周周六
            targetTime = targetTime.plusWeeks(1);
        }

        // 3. 获取延迟时间
        long initialDelay = Duration.between(now, targetTime).toMillis();
		// 4. 周期为每周
        long period = 7 * 24 * 60 * 60 * 1000;

        ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);
        scheduledThreadPool.scheduleAtFixedRate(() -> {
            log.debug("running");
        }, initialDelay, period, TimeUnit.MILLISECONDS);
    }

}

7.5 Fork/Join

7.5.1 概念

Fork/Join 是 JDK 1.7 加入的新的线程池实现,它体现的是一种分治思想,适用于能够进行任务拆分的 cpu 密集型运算。
所谓的任务拆分,是将一个大任务拆分为算法上相同的小任务,直至不能拆分可以直接求解。跟递归相关的一些计算,如归并排序、斐波那契数列、都可以用分治思想进行求解。
Fork/Join 在分治的基础上加入了多线程,可以把每个任务的分解和合并交给不同的线程来完成,进一步提升了运算效率。
Fork/Join 默认会创建与 cpu 核心数大小相同的线程池。

7.5.2 使用

提交给 Fork/Join 线程池的任务需要继承 RecursiveTask(有返回值)或 RecursiveAction(没有返回值),例如下面定义了一个对 1~n 之间的整数求和的任务。

@Slf4j(topic = "c.TestForkJoin")
public class TestForkJoin {

    public static void main(String[] args) {
        ForkJoinPool forkJoinPool = new ForkJoinPool(4);
        log.debug(forkJoinPool.invoke(new AddTask1(5)) + "");
    }

}

@Slf4j(topic = "c.AddTask1")
class AddTask1 extends RecursiveTask<Integer> {
    int n;

    public AddTask1(int n) {
        this.n = n;
    }

    @Override
    public String toString() {
        return "{" + n + '}';
    }

    @Override
    protected Integer compute() {
        if (n == 1) {
            // 如果 n 已经为 1,可以求得结果了
            log.debug("join() -> {}", 1);
            return n;
        }
        // 将任务进行拆分(fork)
        AddTask1 task1 = new AddTask1(n - 1);
        task1.fork();
        log.debug("fork() -> {}+{}", n, task1);
        // 合并(join)结果
        int result = n + task1.join();
        log.debug("join() -> {}+{}={}", n, task1, result);
        return result;
    }
}

结果:

21:52:44.393 c.AddTask1 [ForkJoinPool-1-worker-1] - fork() -> 5+{4}
21:52:44.393 c.AddTask1 [ForkJoinPool-1-worker-3] - fork() -> 3+{2}
21:52:44.393 c.AddTask1 [ForkJoinPool-1-worker-2] - fork() -> 4+{3}
21:52:44.393 c.AddTask1 [ForkJoinPool-1-worker-0] - fork() -> 2+{1}
21:52:44.396 c.AddTask1 [ForkJoinPool-1-worker-3] - join() -> 1
21:52:44.397 c.AddTask1 [ForkJoinPool-1-worker-0] - join() -> 2+{1}=3
21:52:44.397 c.AddTask1 [ForkJoinPool-1-worker-3] - join() -> 3+{2}=6
21:52:44.397 c.AddTask1 [ForkJoinPool-1-worker-2] - join() -> 4+{3}=10
21:52:44.397 c.AddTask1 [ForkJoinPool-1-worker-1] - join() -> 5+{4}=15
21:52:44.397 c.TestForkJoin [main] - 15

用图来表示
![image.png](https://img-blog.csdnimg.cn/img_convert/49688cc3778c9e521d61559d1eff48f3.png#averageHue=#fcfcfc&clientId=u0f90925e-7f91-4&errorMessage=unknown error&from=paste&height=200&id=uea2ea97f&name=image.png&originHeight=250&originWidth=1006&originalType=binary&ratio=1&rotation=0&showTitle=false&size=23105&status=error&style=none&taskId=ubc257ced-31ea-476f-a9ad-3d4038a14bb&title=&width=804.8)
改进:

@Slf4j(topic = "c.TestForkJoin")
public class TestForkJoin {
	
	public static void main(String[] args) {
		ForkJoinPool forkJoinPool = new ForkJoinPool(4);
		//log.debug(forkJoinPool.invoke(new AddTask1(5)) + "");
		log.debug(forkJoinPool.invoke(new AddTask3(1,10)) + "");
	}
	
}
@Slf4j(topic = "c.AddTask3")
class AddTask3 extends RecursiveTask<Integer> {
	int begin;
	int end;
	
	public AddTask3(int begin, int end) {
		this.begin = begin;
		this.end = end;
	}
	
	@Override
	public String toString() {
		return "{" + begin + "," + end + "}";
	}
	
	@Override
	protected Integer compute() {
		if (begin == end) {
			log.debug("join() -> {}", begin);
			return begin;
		}
		if (end - begin == 1) {
			log.debug("join() -> {}+{}={}", begin, end, end + begin);
			return end + begin;
		}
		int mid = (end + begin) / 2;
		// 将任务进行拆分(fork)
		AddTask3 task1 = new AddTask3(begin, mid);
		task1.fork();
		AddTask3 task2 = new AddTask3(mid + 1, end);
		task2.fork();
		log.debug("fork() -> {}+{}", task1, task2);
		// 合并(join)结果
		int result = task1.join() + task2.join();
		log.debug("join() -> {}+{}={}", task1, task2, result);
		return result;
	}
}

结果:

22:04:27.616 c.AddTask3 [ForkJoinPool-1-worker-0] - join() -> 1+2=3
22:04:27.616 c.AddTask3 [ForkJoinPool-1-worker-1] - fork() -> {1,3}+{4,5}
22:04:27.616 c.AddTask3 [ForkJoinPool-1-worker-3] - join() -> 4+5=9
22:04:27.616 c.AddTask3 [ForkJoinPool-1-worker-2] - fork() -> {1,2}+{3,3}
22:04:27.619 c.AddTask3 [ForkJoinPool-1-worker-0] - join() -> 3
22:04:27.619 c.AddTask3 [ForkJoinPool-1-worker-2] - join() -> {1,2}+{3,3}=6
22:04:27.619 c.AddTask3 [ForkJoinPool-1-worker-1] - join() -> {1,3}+{4,5}=15
22:04:27.619 c.TestForkJoin [main] - 15

用图来表示
![image.png](https://img-blog.csdnimg.cn/img_convert/6fbb69451a2529961f0c27715de6e0e4.png#averageHue=#fcfcfc&clientId=u0f90925e-7f91-4&errorMessage=unknown error&from=paste&height=403&id=ud2656131&name=image.png&originHeight=504&originWidth=1036&originalType=binary&ratio=1&rotation=0&showTitle=false&size=55579&status=error&style=none&taskId=ud288f9ae-158d-4a30-9d61-083b46aa6d1&title=&width=828.8)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

层巅余落日

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值