Jam*_*hon 25 java spring multithreading executor
我试图了解如何在使用Spring进行事务管理的Java应用程序中实现线程.我在Spring文档中找到了TaskExecutor部分,而ThreadPoolTaskExecutor看起来很符合我的需求;
ThreadPoolTaskExecutor类
此实现只能在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)
| 归档时间: |
|
| 查看次数: |
86024 次 |
| 最近记录: |