一、线程池的创建方式
方式(一):通过构造函数threadpoolexecutor()方式创建线程池
步骤1:先构建线程池
public class asynctaskexecutor { /** * 核心线程数 */ private static final int corepoolsize = 10; /** * 最大线程数 */ private static final int maxpoolsize = 30; /** * 空闲线程回收时间 * 空闲线程是指:当前线程池中超过了核心线程数之后,多余的空闲线程的数量 */ private static final int keepalivetime = 100; /** * 任务队列/阻塞队列 */ private static final int blockingqueuesize = 99999; private static final threadpoolexecutor executorpool = new threadpoolexecutor( corepoolsize, maxpoolsize, keepalivetime, timeunit.milliseconds, new linkedblockingqueue<>(blockingqueuesize), new threadfactorybuilder().setnameformat("asynctaskthread" + "-%d").build(), new threadpoolexecutor.callerrunspolicy() ); /** * 异步任务执行 * * @param task */ public static void execute(runnable task) { executorpool.execute(task); } }
步骤2:通过实现runnable接口,创建异步任务
@slf4j public class commontask implements runnable { /** * 模块id */ private long modelid; /** * 模块名称 */ private modelenum modelname; /** * 构造方法 * * @param modelid * @param modelname */ public commontask(long modelid, modelenum modelname) { this.modelid = modelid; this.modelname = modelname; } @override public void run() { log.info("start to process common task!!!"); if (modelid.intvalue() == modelenum.chinese.getcode()) { string name = modelenum.chinese.getvalue(); log.info("modelid = {} modelname = {}", modelid, name); } else { modelname = modelenum.forvalue(modelid.intvalue()); log.info("modelid = {} modelname = {}", modelid, modelname.getvalue()); } } }
枚举
public enum modelenum { chinese(1, "语文"), math(2, "数学"), english(3, "数学"); /** * code */ private int code; /** * value */ private string value; /** * 映射结果集 */ private static final map<integer, modelenum> value_map; static { value_map = new hashmap<>(); for (modelenum modelenum : modelenum.values()) { value_map.put(modelenum.code, modelenum); } } modelenum(int code, string value) { this.code = code; this.value = value; } public int getcode() { return code; } public string getvalue() { return value; } /** * 根据code获取枚举实例 * * @param code * @return */ public static modelenum forvalue(int code) { return value_map.get(code); } }
步骤3:验证
//步骤1:创建异步任务 commontask task = new commontask(1l, modelenum.chinese); //步骤2:调用线程池异步执行任务 asynctaskexecutor.execute(task); log.info("main thread over...");
结果如下:
2024-05-23 14:53:16.096 info 20652 --- [ main] com.example.demo.dao.userdaotest : main thread over...
2024-05-23 14:53:16.097 info 20652 --- [ynctaskthread-0] com.example.demo.task.commontask : start to process common task!!!
2024-05-23 14:53:16.097 info 20652 --- [ynctaskthread-0] com.example.demo.task.commontask : modelid = 1 modelname = 语文
方式(二):构建threadpooltaskexecutor线程池,将其声明为bean,可以通过注入bean的方式和在方法上使用@async(“asynctaskexecutor”)这种注解方式使用此线程池
@slf4j @configuration @enableasync public class taskexecutor { @value("${async.executor.thread.core_pool_size}") private int corepoolsize; @value("${async.executor.thread.max_pool_size}") private int maxpoolsize; @value("${async.executor.thread.queue_capacity}") private int queuecapacity; @value("${async.executor.thread.name.deal_task}") private string tasknameprefix; /** * 构建线程池 并将其声明为bean * 方式1:可以通过注入的方式使用此线程池 * 方式2:可以在方法上使用@async("asynctaskexecutor")这种注解方式使用此线程池 * * @return */ @bean(name = "asynctaskexecutor") public executor asynctaskexecutor() { log.info("start asynctaskexecutor..."); threadpooltaskexecutor threadpooltaskexecutor = new threadpooltaskexecutor(); threadpooltaskexecutor.setcorepoolsize(corepoolsize); threadpooltaskexecutor.setmaxpoolsize(maxpoolsize); threadpooltaskexecutor.setqueuecapacity(queuecapacity); threadpooltaskexecutor.setthreadnameprefix(tasknameprefix); //拒绝策略:当前线程数已经达到最大线程数后,如何处理新任务 //callerrunspolicy()不在新线程中执行任务,而是返回调用者所在的线程来执行 threadpooltaskexecutor.setrejectedexecutionhandler( new threadpoolexecutor.callerrunspolicy()); threadpooltaskexecutor.initialize(); return threadpooltaskexecutor; } }
在application.yml中的配置
async: executor: thread: core_pool_size: 10 max_pool_size: 10 queue_capacity: 99999 name: deal_task: deal-task-
使用方式1:在方法上使用@async(“asynctaskexecutor”)这种注解方式使用此线程池
使用方式2:通过注入的方式使用此线程池
@slf4j @service public class workserviceimpl implements workservice { @async("asynctaskexecutor") public void doasynctask() throws interruptedexception { thread.sleep(1000); log.info("do asynctask..."); } }
@slf4j @runwith(springrunner.class) @springboottest public class userdaotest { sqlsession sqlsession; @resource private workservice workservice; @resource private executor asynctaskexecutor; @test public void test() { try { //方式1:在方法上使用@async("asynctaskexecutor")这种注解方式使用此线程池 for (int i = 0; i < 5; i++) { workservice.doasynctask(); } log.info("main thread over..."); //方式2:通过注入的方式使用此线程池(方便) asynctaskexecutor.execute(() -> { log.info("async task is running.."); }); thread.sleep(5000); }catch (exception e) { e.printstacktrace(); } } }
到此这篇关于java线程池实战应用总结的文章就介绍到这了,更多相关java线程池内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论