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

Jam*_*hon 25 java spring multithreading executor

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

ThreadPoolTask​​Executor类

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

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

Jac*_*son 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 );
               }
          });
     }
}
Run Code Online (Sandbox Code Playgroud)

以下是Spring bean:

<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>
Run Code Online (Sandbox Code Playgroud)

  • 如果队列容量大于0,则会创建一个队列,以便特定TaskExecutor触发的任务可以等到池中的线程可用.容量表示队列中有多少个空格.如果队列填满,执行程序将阻塞(即执行方法将不会返回,直到空格打开).这是队列中的文档:http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/LinkedBlockingQueue.html (12认同)
  • 要确保阻塞完整队列/池,您需要将`rejectedExecutionHandler`设置为`java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy`.默认处理程序,AbortPolicy,(http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/scheduling/concurrent/ExecutorConfigurationSupport.html#setRejectedExecutionHandler%28java.util.concurrent.RejectedExecutionHandler% 29)中止任务而不是阻止调用者. (2认同)