温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何正确的使用JDK线程池和Spring线程池

发布时间:2021-03-23 15:05:35 来源:亿速云 阅读:326 作者:Leah 栏目:编程语言

这期内容当中小编将会给大家带来有关如何正确的使用JDK线程池和Spring线程池,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

JDK线程池和Spring线程池实例,异步调用,可以直接使用

(1)JDK线程池的使用,此处采用单例的方式提供,见示例:

public class ThreadPoolUtil {
	private static int corePoolSize = 5;
	private static int maximumPoolSize = 10;
	private static long keepAliveTime = 60L;
	private static TimeUnit unit = TimeUnit.SECONDS;
	private static int capacity = 1024;
	private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder().setNameFormat("jdk-thread-pool-%d").build();
	private static final ExecutorService executorService = new ThreadPoolExecutor(corePoolSize,
	maximumPoolSize,
	keepAliveTime,
	unit,
	new LinkedBlockingQueue<>(capacity),
	namedThreadFactory,
	new ThreadPoolExecutor.AbortPolicy());
	private ThreadPoolUtil () {
	}
	public static ExecutorService getExecutorService () {
		return executorService;
	}
}

在其它地方可以直接这样使用:

ThreadPoolUtil.getExecutorService().execute(() -> {
	System.out.println("test1");
	System.out.println("test2");
}
)

(2)Spring线程池的使用,此处通过配置类的方式配置线程池的相关属性,见示例:

@Configuration
@EnableAsync
public class DocataThreadBeanConfig {
	private int corePoolSize = 5;
	private int maxPoolSize = 10;
	private int queueCapacity = 1024;
	private String namePrefix = "async-service-task-";
	// 上述属性可以通过@Value来读取配置值
	@Bean(name = "asyncServiceTaskExecutor")
	public TaskExecutor asyncServiceExecutor() {
		ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
		// 设置核心线程数
		executor.setCorePoolSize(corePoolSize);
		// 设置最大线程数
		executor.setMaxPoolSize(maxPoolSize);
		// 设置队列容量
		executor.setQueueCapacity(queueCapacity);
		// 设置线程活跃时间(秒)
		executor.setKeepAliveSeconds(60);
		// 设置默认线程名称
		executor.setThreadNamePrefix(namePrefix);
		// 设置拒绝策略
		executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
		// 等待所有任务结束后再关闭线程池
		executor.setWaitForTasksToCompleteOnShutdown(true);
		executor.initialize();
		;
		return executor;
	}
}

在其它文件中需要这样使用:

@Resource(name="asyncServiceTaskExecutor")
private ThreadPoolTaskExecutor asyncServiceTaskExecutor;

不要直接使用@Autowired,否则会提示失败的

@Autowired
private ThreadPoolTaskExecutor asyncServiceTaskExecutor;

上述就是小编为大家分享的如何正确的使用JDK线程池和Spring线程池了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI