当前位置: 首页 > 后端技术 > Java

关于java线程池的创建

时间:2023-04-01 17:38:29 Java

线程池提供了解决线程生命周期开销和资源不足的问题。通过为多个任务重用线程,线程创建的开销被分摊到多个任务中。好处是由于请求到达时线程已经存在,线程创建引入的延迟也被无意间消除了。这样,请求立即得到服务,使应用程序响应更快。并且通过适当调整线程池中的线程数,即当请求数超过一定的阈值时,其他新到达的请求将强制等待,直到获得线程进行处理,从而防止资源短缺。使用spring管理线程池的使用1.创建线程池配置信息threads.properties####业务线程池配置#####是否启用自定义线程池。当为true时,以下参数将生效handler.threads.custom=false#核心线程数handler.threads.corePoolSize=20#最大线程数handler.threads.maximumPoolSize=1000#空闲线程存活时间,单位秒handler。threads.keepAliveTime=100#工作队列大小,0为无限handler.threads.workQueue=02,创建线程池配置,ThreadsPoolConfig.javapackagecom.hk.core.concurrent;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.stereotype.Component;/***线程池配置*/@ComponentpublicclassThreadsPoolConfig{/***是否启用自定义线程池*/@Value("${handler.threads.custom}")private布尔自定义;/***核心线程数*/@Value("${handler.threads.corePoolSize}")privateintcorePoolSize;/***线程池最大线程数*/@Value("${handler.threads.maximumPoolSize}}")privateintmaximumPoolSize;/***空闲线程存活时间(核心线程无效)*/@Value("${handler.threads.keepAliveTime}")privatelongkeepAliveTime;/***任务队列大小,0为无界队列*/@Value("${handler.threads.workQueue}")privateintworkQueue;publicbooleanisCustom(){returncustom;}publicvoidsetCustom(booleancustom){this.custom=custom;}publicintgetCorePoolSize(){returncorePoolSize;}publicvoidsetCorePoolSize(intcorePoolSize){this.corePoolSize=corePoolSize;}publicintgetMaximumPoolSize(){returnmaximumPoolSize;}publicvoidsetMaximumPoolSize(intmaximumPoolSize){this.maximumPoolSize=maximumPoolSize;}publiclonggetKeepAliveTime(){returnkeepAliveTime;}publicvoidsetKeepAliveTime(longkeepAliveTime){this.keepAliveTime=keepAliveTime;}publicintgetWorkQueue(){returnworkQueue;}publicvoidsetWorkQueue(intworkQueue){this.workQueue=workQueue;}}3、创建线程池处理器管理线程HandlerThreadsPool.javapackagecom.hk.core.concurrent;导入java.util.concurrent.BlockingQueue;导入java.util.concurrent.ExecutorService;导入java.util.concurrent.Executors;导入java.util.concurrent.LinkedBlockingQueue;导入java.util.concurrent.ThreadPoolExecutor;导入java.util.concurrent.TimeUnit;导入javax。annotation.PreDestroy;/***线程管理器*/publicclassHandlerThreadsPool{publicExecutorServiceexecutorService;publicHandlerThreadsPool(){//TODO自动生成的构造函数存根this.executorService=Executors.newCachedThreadPool();}publicHandlerThreadsPool(ThreadsPoolConfigconfig){//TODO自动生成的构造函数存根if(config.isCustom()){BlockingQueuequeue=null;if(config.getWorkQueue()>0){queue=newLinkedBlockingQueue(config.getWorkQueue());//通常使用LinkedBlockingQueue队列}else{queue=newLinkedBlockingQueue();}       //配置线路程序池信息this.executorService=newThreadPoolExecutor(config.getCorePoolSize(),config.getMaximumPoolSize(),config.getKeepAliveTime(),TimeUnit.SECONDS,queue,newThreadPoolExecutor.AbortPolicy()//拒绝策略,任务队列满后,一个新任务将被丢弃并抛出异常);}else{this.executorService=Executors.newCachedThreadPool();}}/*   *创建线程并为线程处理事件*/publicvoidexecute(Runnablerunnable){executorService.执行(可运行);}/*  *对象销毁时,销毁线程  */@PreDestroypublicvoidstop(){executorService.shutdown();}}4。使用线程池包com.hk.core.concurrent;importjavax.annotation.PostConstruct;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.stereotype.Service;@ServicepublicclassMsgHandlerimplementsRunnable{@自动装配私有ThreadsPoolConfig配置;//注入配置@Overridepublicvoidrun(){//在这里写处理逻辑System.out.println("Createathreadtoprocessthetransaction....");}@PostConstructpublicvoidloadThreadsPool(){//初始化线程池HandlerThreadsPoolhandlerThreadsPool=newHandlerThreadsPool(config);//调用线程池,创建线程处理事件handlerThreadsPool.execute(newMsgHandler());}}关系中断线程的使用(略)//线程,可用基于固定线程池大小,重复动作使用一个线程强制停止newThread(()->{},"线程名称").start();//方法privatestaticbooleanthreadIsRunning(){booleanflag=false;//getAllStackTraces()方法的作用是返回所有活动线程的堆栈跟踪图。映射键是线程,而每个映射值是一个StackTraceElement数组,表示相应线程的堆栈转储。返回的堆栈跟踪的格式是为getStackTrace方法指定的。在调用此方法的同时可能正在执行一个线程。每个线程的堆栈跟踪只代表一个快照,每个堆栈跟踪可以在不同的时间获得。如果虚拟机没有线程的堆栈跟踪,则在映射值中返回一个零长度数组。for(Threadt:Thread.getAllStackTraces().keySet()){if("线程名称".equals(t.getName())){LOG.info("发送上一个线程中断命令...");//interrupt()方法是中断对应的线程t.interrupt();LOG.info("中断命令已发送");标志=真;}}返回标志;}