gpt4 book ai didi

java - 任何带有 TaskExecutor 示例的好的 Spring 线程?

转载 作者:IT老高 更新时间:2023-10-28 13:47:11 25 4
gpt4 key购买 nike

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

ThreadPoolTaskExecutor

This implementation can only be used in a Java 5 environment but is also the most commonly used one in that environment. It exposes bean properties for configuring a java.util.concurrent.ThreadPoolExecutor and wraps it in a TaskExecutor. If you need something advanced such as a ScheduledThreadPoolExecutor, it is recommended that you use a ConcurrentTaskExecutor instead.

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

最佳答案

这很简单。这个想法是你有一个 executor 对象,它是一个 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 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>

关于java - 任何带有 TaskExecutor 示例的好的 Spring 线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/852743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com