有没有好的带有 TaskExecutor 的 Spring 线程示例? [关闭]

2024-05-09

我试图了解如何在使用 Spring 进行事务管理的 Java 应用程序中实现线程。我在中找到了 TaskExecutor 部分Spring文档 http://static.springframework.org/spring/docs/2.5.x/reference/scheduling.html#scheduling-task-executor,并且 ThreadPoolTask​​Executor 看起来很适合我的需求;

线程池任务执行器

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

但是我不知道如何使用它。我一段时间以来一直在寻找好的例子,但没有运气。如果有人可以帮助我,我将不胜感激。


这很简单。这个想法是,你有一个执行器对象,它是一个 bean,它被传递到任何想要触发新任务的对象(在新线程中)。好处是,您只需更改 Spring 配置即可修改要使用的任务执行器类型。在下面的示例中,我将使用一些示例类 (ClassWithMethodToFire) 并将其包装在 Runnable 对象中来执行火灾;您还可以在自己的类中实际实现 Runnable ,然后在您只需调用的执行方法中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 );
               }
          });
     }
}

这是 Spring beans:

<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>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

有没有好的带有 TaskExecutor 的 Spring 线程示例? [关闭] 的相关文章

随机推荐