Spring線程池ThreadPoolExecutor配置并且得到任務執(zhí)行的結(jié)果
用ThreadPoolExecutor的時候,又想知道被執(zhí)行的任務的執(zhí)行情況,這時就可以用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;
// 保存任務所需要的數(shù)據(jù)
private Object threadPoolTaskData;
private static int consumeTaskSleepTime = 2000;
public ThreadPoolTask(Object tasks) {
this.threadPoolTaskData = tasks;
}
public synchronized String call() throws Exception {
// 處理一個任務,這里的處理方式太簡單了,僅僅是一個打印語句
System.out.println("開始執(zhí)行任務:" + threadPoolTaskData);
String result = "";
// //便于觀察,等待一段時間
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;
}
}
模擬客戶端提交的線程
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)建任務并提交到線程池中:" + task);
FutureTask<String> futureTask = new FutureTask<String>(
new ThreadPoolTask(task));
threadPoolTaskExecutor.execute(futureTask);
// 在這里可以做別的任何事情
String result = null;
try {
// 取得結(jié)果,同時設置超時執(zhí)行時間為0.1秒。同樣可以用future.get(),不設置執(zhí)行超時時間取得結(jié)果
result = futureTask.get();
} catch (InterruptedException e) {
futureTask.cancel(true);
} catch (ExecutionException e) {
futureTask.cancel(true);
} catch (Exception e) {
futureTask.cancel(true);
// 超時后,進行相應處理
} 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" /> <!-- 事務管理器 --> <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命名空間配置事務管理,這里對service包下的服務類方法提供事務 --> <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ù),默認為1 --> <property name="corePoolSize" value="10" /> <!-- 最大線程數(shù),默認為Integer.MAX_VALUE --> <property name="maxPoolSize" value="50" /> <!-- 隊列最大長度,一般需要設置值>=notifyScheduledMainExecutor.maxNum;默認為Integer.MAX_VALUE <property name="queueCapacity" value="1000" /> --> <!-- 線程池維護線程所允許的空閑時間,默認為60s --> <property name="keepAliveSeconds" value="300" /> <!-- 線程池對拒絕任務(無線程可用)的處理策略,目前只支持AbortPolicy、CallerRunsPolicy;默認為后者 --> <property name="rejectedExecutionHandler"> <!-- AbortPolicy:直接拋出java.util.concurrent.RejectedExecutionException異常 --> <!-- CallerRunsPolicy:主線程直接執(zhí)行該任務,執(zhí)行完之后嘗試添加下一個任務到線程池中,可以有效降低向線程池內(nèi)添加任務的速度 --> <!-- DiscardOldestPolicy:拋棄舊的任務、暫不支持;會導致被丟棄的任務無法再次被執(zhí)行 --> <!-- DiscardPolicy:拋棄當前任務、暫不支持;會導致被丟棄的任務無法再次被執(zhí)行 --> <bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy" /> </property> </bean> </beans>
測試類
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)造一個線程池
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();
}
}
}
項目截圖(基于maven構(gòu)建)

運行截圖:

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

總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內(nèi)容請查看下面相關鏈接
相關文章
Java數(shù)據(jù)結(jié)構(gòu)徹底理解關于KMP算法
這篇文章主要介紹了Java數(shù)據(jù)結(jié)構(gòu)關于KMP算法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-09-09
Java實現(xiàn)貪吃蛇大作戰(zhàn)小游戲的示例代碼
本文主要介紹了Java實現(xiàn)貪吃蛇大作戰(zhàn)小游戲的示例代碼,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2022-07-07
Java swing框架實現(xiàn)的貪吃蛇游戲完整示例
這篇文章主要介紹了Java swing框架實現(xiàn)的貪吃蛇游戲,結(jié)合完整實例形式分析了java使用swing框架結(jié)合awt圖形繪制實現(xiàn)貪吃蛇游戲的具體步驟與相關實現(xiàn)技巧,需要的朋友可以參考下2017-12-12
Spring?Security中自定義cors配置及原理解析
在Spring框架中,通過自定義CORS配置可根據(jù)實際情況調(diào)整URL的協(xié)議、主機、端口等,以適應"同源安全策略",配置原理涉及CorsConfigurer和CorsFilter,自定義配置需要注意@Configuration注解、方法名以及可能的@Autowired注解2024-10-10
Springboot和bootstrap實現(xiàn)shiro權(quán)限控制配置過程
這篇文章主要介紹了Springboot和bootstrap實現(xiàn)shiro權(quán)限控制,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-04-04

