使用TaskExecutor示例的任何好的Spring线程?

时间:2009-05-12 13:20:06

标签: java multithreading spring executor

我正试图了解如何在使用Spring进行事务管理的Java应用程序中实现线程。我在Spring documentation找到了TaskExecutor部分,而ThreadPoolTask​​Executor看起来很符合我的需要;

  

ThreadPoolTask​​Executor类

     

此实现只能在Java 5环境中使用,但也是该环境中最常用的实现。它公开了bean属性,用于配置java.util.concurrent.ThreadPoolExecutor并将其包装在TaskExecutor中。如果您需要一些高级的东西,例如ScheduledThreadPoolExecutor,建议您使用ConcurrentTaskExecutor。

但是我不知道如何使用它。我一直在寻找好的例子现在没有运气。如果有人可以帮助我,我会很感激。

1 个答案:

答案 0 :(得分:34)

这很简单。这个想法是你有一个执行者对象,它是一个bean,它被传递给任何想要触发新任务的对象(在一个新线程中)。好处是您可以通过更改Spring配置来修改要使用的任务类型的任务执行器。在下面的例子中,我将采用一些示例类(ClassWithMethodToFire)并将其包装在Runnable对象中以进行解雇;你也可以在你自己的类中实际运行Runnable,然后在execute方法中调用classWithMethodToFire.run()

这是一个非常简单的例子。

public class SomethingThatShouldHappenInAThread {
     private TaskExecutor taskExecutor;
     private ClassWithMethodToFire classWithMethodToFire;

     public SomethingThatShouldHappenInAThread(TaskExecutor taskExecutor,
                                               ClassWithMethodToFire classWithMethodToFire) {
          this.taskExecutor = taskExecutor;
          this.classWithMethodToFire = classWithMethodToFire;
     }

     public void fire(final SomeParameterClass parameter) {
          taskExecutor.execute( new Runnable() {
               public void run() {
                    classWithMethodToFire.doSomething( parameter );
               }
          });
     }
}

以下是春豆:

<bean name="somethingThatShouldHappenInAThread" class="package.name.SomethingThatShouldHappenInAThread">
     <constructor-arg type="org.springframework.core.task.TaskExecutor" ref="taskExecutor" />
     <constructor-arg type="package.name.ClassWithMethodToFire" ref="classWithMethodToFireBean"/>
</bean>

<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
     <property name="corePoolSize" value="5" />
     <property name="maxPoolSize" value="10" />
     <property name="queueCapacity" value="25" />
</bean>
相关问题