好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Spring线程池ThreadPoolExecutor配置并且得到任务执行的结果

用threadpoolexecutor的时候,又想知道被执行的任务的执行情况,这时就可以用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( "开始执行任务:" + 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( "创建任务并提交到线程池中:" + task);

  futuretask<string> futuretask = new futuretask<string>(

  new threadpooltask(task));

  threadpooltaskexecutor.execute(futuretask);

  // 在这里可以做别的任何事情

  string result = null ;

  try {

  // 取得结果,同时设置超时执行时间为0.1秒。同样可以用future.get(),不设置执行超时时间取得结果

  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://HdhCmsTestspringframework.org/schema/beans"

  xmlns:xsi= "http://HdhCmsTestw3.org/2001/xmlschema-instance"

  xmlns:p= "http://HdhCmsTestspringframework.org/schema/p"

  xmlns:aop= "http://HdhCmsTestspringframework.org/schema/aop"

  xmlns:tx= "http://HdhCmsTestspringframework.org/schema/tx"

  xsi:schemalocation="

http: //HdhCmsTestspringframework.org/schema/beans http://HdhCmsTestspringframework.org/schema/beans/spring-beans-2.5.xsd

http: //HdhCmsTestspringframework.org/schema/tx http://HdhCmsTestspringframework.org/schema/tx/spring-tx-2.5.xsd

http: //HdhCmsTestspringframework.org/schema/aop http://HdhCmsTestspringframework.org/schema/aop/spring-aop-2.5.xsd">

  <!-- 配置数据源 -->

  <bean id= "datasource" class = "org.apache测试数据mons.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:主线程直接执行该任务,执行完之后尝试添加下一个任务到线程池中,可以有效降低向线程池内添加任务的速度 -->

  <!-- discardoldestpolicy:抛弃旧的任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->

  <!-- discardpolicy:抛弃当前任务、暂不支持;会导致被丢弃的任务无法再次被执行 -->

  <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忙执行超过1秒的会返回null

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:http://HdhCmsTestblogjava.net/paulwong/archive/2011/12/07/365773.html

查看更多关于Spring线程池ThreadPoolExecutor配置并且得到任务执行的结果的详细内容...

  阅读:12次