SpringBoot线程池使用详解

前提摘要:

    基于Springboot 2.1.4.RELEASE

 

▎ 配置TaskExecutor

import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@Configuration
@EnableAsync
public class ThreadPoolConfig {

	@Bean
	public TaskExecutor taskExecutor() {

		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

		// 设置核心线程数
		executor.setCorePoolSize(5);

		// 设置最大线程数
		executor.setMaxPoolSize(10);

		// 设置队列容量
		executor.setQueueCapacity(5);

		// 设置线程活跃时间,单位秒
		executor.setKeepAliveSeconds(60);

		// 设置核心线程超时回收
		executor.setAllowCoreThreadTimeOut(true);

		// 设置默认线程名称
		executor.setThreadNamePrefix("IThread-");

		// 设置拒绝策略
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());

		return executor;

	}
}

▎ 参数解读

● CorePoolSize

核心线程数,核心线程会一直存活,即使没有任务需要处理。当线程数小于核心线程数时,即使现有的线程空闲,线程池也会优先创建新线程来处理任务,而不是直接交给现有的线程处理。

核心线程在allowCoreThreadTimeout被设置为true时会超时退出,默认情况下不会退出。

● MaxPoolSize

当线程数大于或等于核心线程,且任务队列已满时,线程池会创建新的线程,直到线程数量达到maxPoolSize。如果线程数已等于maxPoolSize,且任务队列已满,则已超出线程池的处理能力,线程池会拒绝处理任务而抛出异常。

● queueCapacity
任务队列容量。从maxPoolSize的描述上可以看出,任务队列的容量会影响到线程的变化,因此任务队列的长度也需要恰当的设置。

● keepAliveTime

当线程空闲时间达到keepAliveTime,该线程会退出,直到线程数量等于corePoolSize。如果allowCoreThreadTimeout设置为true,则所有线程均会退出直到线程数量为0。

● allowCoreThreadTimeout
是否允许核心线程空闲退出,默认值为false。

● RejectedExecutionHandler

拒绝策略:当线程数大于MaxPoolSize+queueCapacity被触发:

  ☞ CallerRunsPolicy - 当触发拒绝策略,只要线程池没有关闭的话,则使用调用线程直接运行任务。一般并发比较小,性能要求不高,不允许失败。但是,由于调用者自己运行任务,如果任务提交速度过快,可能导致程序阻塞,性能效率上必然的损失较大

    ☞ AbortPolicy - 丢弃任务,并抛出拒绝执行 RejectedExecutionException 异常信息。线程池默认的拒绝策略。必须处理好抛出的异常,否则会打断当前的执行流程,影响后续的任务执行。

  ☞ DiscardPolicy - 直接丢弃,其他啥都没有

  ☞ DiscardOldestPolicy -  当触发拒绝策略,只要线程池没有关闭的话,丢弃阻塞队列 workQueue 中最老的一个任务,并将新任务加入

 

▎ 线程池执行流程图   图片来源:https://www.cnblogs.com/yw0219/p/8810956.html

 

▎ 案例: 使用AbortPolicy拒绝策略,模拟高并发触发异常

☞ TaskExecutor配置

@Bean
public TaskExecutor taskExecutor() {
	ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
	// 设置核心线程数
	executor.setCorePoolSize(5);
	// 设置最大线程数
	executor.setMaxPoolSize(10);
	// 设置队列容量
	executor.setQueueCapacity(5);
	// 设置线程活跃时间,单位秒
	executor.setKeepAliveSeconds(60);
	// 设置核心线程超时回收
	executor.setAllowCoreThreadTimeOut(true);
	// 设置默认线程名称
	executor.setThreadNamePrefix("IThread-");
	// 设置拒绝策略
	executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
	return executor;
}

☞ 创建异步任务

ExecutorService

public interface ExecutorService {
	public void exec();
}

ExecutorServiceImpl

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.mote.service.ExecutorService;

@Service("executorService")
public class ExecutorServiceImpl implements ExecutorService {

	private Logger log = LoggerFactory.getLogger(getClass());

	@Override
	@Async
	public void exec() {
		log.info(Thread.currentThread().getName() + "开始执行");

		try {
			// 模拟业务处理耗时
			Thread.sleep(10000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		log.info("<<<<<<<<<<<<<<<<线程执行完毕>>>>>>>>>>>>>>>>");
	}

}

☞ 编写Controller,调用异步任务

ExecutorController

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.mote.service.ExecutorService;

@RestController
public class ExecutorController {

	@Autowired
	private ExecutorService executorService;

	@GetMapping("/executor")
	public String executor() {
		try {
			executorService.exec();
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "error";
	}
}

 

☞ 打开浏览器,访问Controller接口,不断刷新模拟高并发,观察返回结果,如果出现error说明策略被触发了

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CountDownLatch 是一个非常实用的多线程工具类,它可以让一个或多个线程等待其他线程完成执行后再继续执行。在多线程编程中,我们经常需要等待某些任务完成后才能进行下一步操作,这时就可以使用 CountDownLatch 来实现。 配合线程池使用 CountDownLatch 的基本思路如下: 1. 创建一个 CountDownLatch 对象,并设置计数器初始值为需要等待的线程数。 2. 创建一个线程池,然后提交需要等待执行的任务。 3. 在任务中调用 CountDownLatch 的 countDown() 方法来减少计数器的值。 4. 在主线程中调用 CountDownLatch 的 await() 方法来等待所有任务执行完毕。 下面是一个简单的示例代码: ```java import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { int threadCount = 5; CountDownLatch latch = new CountDownLatch(threadCount); ExecutorService executorService = Executors.newFixedThreadPool(threadCount); for (int i = 0; i < threadCount; i++) { executorService.submit(new Worker(latch)); } latch.await(); System.out.println("All tasks are finished"); executorService.shutdown(); } static class Worker implements Runnable { private final CountDownLatch latch; public Worker(CountDownLatch latch) { this.latch = latch; } @Override public void run() { try { // 模拟执行任务 Thread.sleep((long) (Math.random() * 10000)); System.out.println(Thread.currentThread().getName() + " has finished the task"); } catch (InterruptedException e) { e.printStackTrace(); } finally { latch.countDown(); } } } } ``` 在上面的示例代码中,我们创建了一个 CountDownLatch 对象,计数器的初始值为 5。然后创建了一个线程池,提交了 5 个任务,并在任务中模拟了一定的执行时间。每个任务执行完毕后都会调用 CountDownLatch 的 countDown() 方法来减少计数器的值。最后,在主线程中调用 CountDownLatch 的 await() 方法来等待所有任务执行完毕。当所有任务都完成后,输出 "All tasks are finished"。 需要注意的是,在使用 CountDownLatch 时,计数器的初始值要与需要等待的线程数相等,否则可能会出现死锁的情况。另外,CountDownLatch 只能使用一次,计数器的值减少到 0 后就无法重置。如果需要重复使用,可以考虑使用 CyclicBarrier 或 Semaphore。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值