用threadpoolexecutor的時候,又想知道被執(zhí)行的任務的執(zhí)行情況,這時就可以用futuretask。
threadpooltask
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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 ; // 保存任務所需要的數據 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; } } |
模擬客戶端提交的線程
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
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 { // 取得結果,同時設置超時執(zhí)行時間為0.1秒。同樣可以用future.get(),不設置執(zhí)行超時時間取得結果 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配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
<?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"> <!-- 配置數據源 --> <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" > <!-- 核心線程數,默認為 1 --> <property name= "corepoolsize" value= "10" /> <!-- 最大線程數,默認為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í)行完之后嘗試添加下一個任務到線程池中,可以有效降低向線程池內添加任務的速度 --> <!-- discardoldestpolicy:拋棄舊的任務、暫不支持;會導致被丟棄的任務無法再次被執(zhí)行 --> <!-- discardpolicy:拋棄當前任務、暫不支持;會導致被丟棄的任務無法再次被執(zhí)行 --> <bean class = "java.util.concurrent.threadpoolexecutor$callerrunspolicy" /> </property> </bean> </beans> |
測試類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
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() { // 構造一個線程池 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構建)
運行截圖:
如果遇到cpu忙執(zhí)行超過1秒的會返回null
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對服務器之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
原文鏈接:http://www.blogjava.net/paulwong/archive/2011/12/07/365773.html