您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

带有TaskExecutor示例的Spring线程?

带有TaskExecutor示例的Spring线程?

很简单 这个想法是,你有一个Bean的executor对象,该对象被传递到想要触发新任务的任何对象中(在新线程中)。令人高兴的是,你只需更改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 );
               }
          });
     }
}

And here are the 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>
Java 2022/1/1 18:15:08 有531人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶