Spring線程池ThreadPoolExecutor配置并且得到任務(wù)執(zhí)行的結(jié)果
用ThreadPoolExecutor的時(shí)候,又想知道被執(zhí)行的任務(wù)的執(zhí)行情況,這時(shí)就可以用FutureTask。
ThreadPoolTask
package com.paul.threadPool;
import java.io.Serializable;
import java.util.concurrent.Callable;
public class ThreadPoolTask implements Callable<String>, Serializable {
private static final long serialVersionUID = 0;
// 保存任務(wù)所需要的數(shù)據(jù)
private Object threadPoolTaskData;
private static int consumeTaskSleepTime = 2000;
public ThreadPoolTask(Object tasks) {
this.threadPoolTaskData = tasks;
}
public synchronized String call() throws Exception {
// 處理一個(gè)任務(wù),這里的處理方式太簡(jiǎn)單了,僅僅是一個(gè)打印語(yǔ)句
System.out.println("開(kāi)始執(zhí)行任務(wù):" + threadPoolTaskData);
String result = "";
// //便于觀察,等待一段時(shí)間
try {
// long r = 5/0;
for ( int i= 0 ; i< 100000000 ; i++){
}
result = "OK";
} catch (Exception e) {
e.printStackTrace();
result = "ERROR";
}
threadPoolTaskData = null;
return result;
}
}
模擬客戶(hù)端提交的線程
package com.paul.threadPool;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
public class StartTaskThread implements Runnable{
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
private int i;
public StartTaskThread(ThreadPoolTaskExecutor threadPoolTaskExecutor,int i)
{
this.threadPoolTaskExecutor = threadPoolTaskExecutor;
this.i = i;
}
@Override
public synchronized void run() {
String task = "task@ " + i;
System.out.println("創(chuàng)建任務(wù)并提交到線程池中:" + task);
FutureTask<String> futureTask = new FutureTask<String>(
new ThreadPoolTask(task));
threadPoolTaskExecutor.execute(futureTask);
// 在這里可以做別的任何事情
String result = null;
try {
// 取得結(jié)果,同時(shí)設(shè)置超時(shí)執(zhí)行時(shí)間為0.1秒。同樣可以用future.get(),不設(shè)置執(zhí)行超時(shí)時(shí)間取得結(jié)果
result = futureTask.get();
} catch (InterruptedException e) {
futureTask.cancel(true);
} catch (ExecutionException e) {
futureTask.cancel(true);
} catch (Exception e) {
futureTask.cancel(true);
// 超時(shí)后,進(jìn)行相應(yīng)處理
} finally {
System.out.println("task@" + i + ":result=" + result);
}
}
SPRING配置文件
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"> <!-- 配置數(shù)據(jù)源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="com.mysql.jdbc.Driver" p:url="jdbc:mysql://localhost:3306/mb_main?useUnicode=true&characterEncoding=UTF-8&useServerPrepStmts=true" p:username="root" p:password="1234" /> <!-- 配置Jdbc模板 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" p:dataSource-ref="dataSource" /> <!-- 事務(wù)管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource" /> <tx:advice id="jdbcTxAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" /> </tx:attributes> </tx:advice> <!-- 使用aop/tx命名空間配置事務(wù)管理,這里對(duì)service包下的服務(wù)類(lèi)方法提供事務(wù) --> <aop:config> <aop:pointcut id="jdbcServiceMethod" expression="within(com.baobaotao.service..*)" /> <aop:advisor pointcut-ref="jdbcServiceMethod" advice-ref="jdbcTxAdvice" /> </aop:config> <!-- 配置dao <bean id="loginLogDao" class="com.baobaotao.dao.LoginLogDao" p:jdbcTemplate-ref="jdbcTemplate" /> <bean id="userDao" class="com.baobaotao.dao.UserDao" p:jdbcTemplate-ref="jdbcTemplate" /> <bean id="userService" class="com.baobaotao.service.UserService" p:userDao-ref="userDao" p:loginLogDao-ref="loginLogDao" /> --> <bean id="threadPoolTaskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"> <!-- 核心線程數(shù),默認(rèn)為1 --> <property name="corePoolSize" value="10" /> <!-- 最大線程數(shù),默認(rèn)為Integer.MAX_VALUE --> <property name="maxPoolSize" value="50" /> <!-- 隊(duì)列最大長(zhǎng)度,一般需要設(shè)置值>=notifyScheduledMainExecutor.maxNum;默認(rèn)為Integer.MAX_VALUE <property name="queueCapacity" value="1000" /> --> <!-- 線程池維護(hù)線程所允許的空閑時(shí)間,默認(rèn)為60s --> <property name="keepAliveSeconds" value="300" /> <!-- 線程池對(duì)拒絕任務(wù)(無(wú)線程可用)的處理策略,目前只支持AbortPolicy、CallerRunsPolicy;默認(rèn)為后者 --> <property name="rejectedExecutionHandler"> <!-- AbortPolicy:直接拋出java.util.concurrent.RejectedExecutionException異常 --> <!-- CallerRunsPolicy:主線程直接執(zhí)行該任務(wù),執(zhí)行完之后嘗試添加下一個(gè)任務(wù)到線程池中,可以有效降低向線程池內(nèi)添加任務(wù)的速度 --> <!-- DiscardOldestPolicy:拋棄舊的任務(wù)、暫不支持;會(huì)導(dǎo)致被丟棄的任務(wù)無(wú)法再次被執(zhí)行 --> <!-- DiscardPolicy:拋棄當(dāng)前任務(wù)、暫不支持;會(huì)導(dǎo)致被丟棄的任務(wù)無(wú)法再次被執(zhí)行 --> <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" /> </property> </bean> </beans>
測(cè)試類(lèi)
package com.paul.threadPool;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
@ContextConfiguration
public class TestThreadPool extends AbstractJUnit4SpringContextTests{
private static int produceTaskSleepTime = 10;
private static int produceTaskMaxNumber = 1000;
@Autowired
private ThreadPoolTaskExecutor threadPoolTaskExecutor;
public ThreadPoolTaskExecutor getThreadPoolTaskExecutor() {
return threadPoolTaskExecutor;
}
public void setThreadPoolTaskExecutor(
ThreadPoolTaskExecutor threadPoolTaskExecutor) {
this.threadPoolTaskExecutor = threadPoolTaskExecutor;
}
@Test
public void testThreadPoolExecutor()
{
// 構(gòu)造一個(gè)線程池
final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(2, 4, 600,
TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3),
new ThreadPoolExecutor.CallerRunsPolicy());
for (int i = 1; i <= produceTaskMaxNumber; i++) {
try {
Thread.sleep(produceTaskSleepTime);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
new Thread(new StartTaskThread(threadPoolTaskExecutor,i)).start();
}
}
}
項(xiàng)目截圖(基于maven構(gòu)建)

運(yùn)行截圖:

如果遇到cpu忙執(zhí)行超過(guò)1秒的會(huì)返回null

總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。如果你想了解更多相關(guān)內(nèi)容請(qǐng)查看下面相關(guān)鏈接
- python 多進(jìn)程并行編程 ProcessPoolExecutor的實(shí)現(xiàn)
- java 定時(shí)器線程池(ScheduledThreadPoolExecutor)的實(shí)現(xiàn)
- Java線程池ThreadPoolExecutor原理及使用實(shí)例
- 解決python ThreadPoolExecutor 線程池中的異常捕獲問(wèn)題
- ThreadPoolExecutor線程池的使用方法
- Java ThreadPoolExecutor 線程池的使用介紹
- ThreadPoolExecutor線程池原理及其execute方法(詳解)
- 線程池ThreadPoolExecutor并行處理實(shí)現(xiàn)代碼
相關(guān)文章
Java的DelayQueue延遲隊(duì)列簡(jiǎn)單使用代碼實(shí)例
這篇文章主要介紹了Java的DelayQueue延遲隊(duì)列簡(jiǎn)單使用代碼實(shí)例,DelayQueue是一個(gè)延遲隊(duì)列,插入隊(duì)列的數(shù)據(jù)只有達(dá)到設(shè)置的延遲時(shí)間時(shí)才能被取出,否則線程會(huì)被阻塞,插入隊(duì)列的對(duì)象必須實(shí)現(xiàn)Delayed接口,需要的朋友可以參考下2023-12-12
使用eclipse導(dǎo)入javaWeb項(xiàng)目的圖文教程
這篇文章主要介紹了如何使用eclipse導(dǎo)入別人的javaWeb項(xiàng)目,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07
Java類(lèi)的加載時(shí)機(jī)與過(guò)程
這篇文章主要介紹了Java類(lèi)的加載時(shí)機(jī)與過(guò)程,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2021-12-12
實(shí)例講解Java的MyBatis框架對(duì)MySQL中數(shù)據(jù)的關(guān)聯(lián)查詢(xún)
這里我們來(lái)以實(shí)例講解Java的MyBatis框架對(duì)MySQL中數(shù)據(jù)的關(guān)聯(lián)查詢(xún),包括一對(duì)多、多對(duì)一的關(guān)聯(lián)查詢(xún)以及自身關(guān)聯(lián)映射的方法等,需要的朋友可以參考下2016-06-06
基于Java實(shí)現(xiàn)無(wú)向環(huán)和有向環(huán)的檢測(cè)
這篇文章主要介紹了如何在?Java?中實(shí)現(xiàn)無(wú)向環(huán)和有向環(huán)的檢測(cè),文中的示例代碼講解詳細(xì),對(duì)我們學(xué)習(xí)Java有一定的幫助,需要的可以參考一下2022-04-04
SSH框架網(wǎng)上商城項(xiàng)目第2戰(zhàn)之基本增刪查改、Service和Action的抽取
SSH框架網(wǎng)上商城項(xiàng)目第2戰(zhàn)之基本增刪查改、Service和Action的抽取,感興趣的小伙伴們可以參考一下2016-05-05
idea創(chuàng)建springboot項(xiàng)目(版本只能選擇17和21)的解決方法
idea2023創(chuàng)建spring boot項(xiàng)目時(shí),java版本無(wú)法選擇11,本文主要介紹了idea創(chuàng)建springboot項(xiàng)目(版本只能選擇17和21),下面就來(lái)介紹一下解決方法,感興趣的可以了解一下2024-01-01

