
深入理解自定义线程池的 initialize() 方法
在构建自定义线程池时,你可能会注意到 initialize() 方法。 许多开发者在未显式调用此方法时,程序也能正常运行,从而引发疑问:initialize() 方法究竟有何作用?
问题: 我在配置自定义线程池时省略了 initialize() 方法,程序依然正常运行,这是为什么?
解答: 关键在于 spring 框架的自动调用。
让我们先来看一个不使用 spring 的例子:
public class sometest {
public static void main(string[] args) {
threadpooltaskexecutor executor = new threadpooltaskexecutor();
executor.submit(() -> system.out.println("!"));
}
}运行这段代码会抛出异常:“threadpooltaskexecutor not initialized”。 这是因为 threadpooltaskexecutor 没有被正确初始化。
现在,让我们使用 spring boot 来管理线程池:
@springbootapplication
public class demoapplication {
public static void main(string[] args) {
configurableapplicationcontext context = springapplication.run(demoapplication.class, args);
threadpooltaskexecutor myexecutor = context.getbean("myexecutor", threadpooltaskexecutor.class);
myexecutor.submit(() -> system.out.println("hello!"));
}
@bean
public threadpooltaskexecutor myexecutor() {
return new threadpooltaskexecutor();
}
}这段代码能够正常运行。这是因为 spring 框架自动调用了 initialize() 方法。
spring 如何做到这一点呢? 答案在于 executorconfigurationsupport 类:
@override
public void afterpropertiesset() {
initialize();
}afterpropertiesset() 方法是 initializingbean 接口的一部分。 spring bean 的生命周期中,在 bean 初始化完成后,spring 会自动调用 afterpropertiesset(),而此方法内部调用了 initialize() 方法来完成线程池的初始化工作。
因此,当你在 spring 容器中使用线程池时,即使你没有显式调用 initialize(),spring 也会自动完成初始化过程,所以程序能够正常运行。 这并不意味着 initialize() 方法可有可无,它依然负责线程池的关键初始化步骤,只是 spring 帮你完成了这一调用。
以上就是我在配置自定义线程池时没有配置initialize()方法,为什么程序仍然可以正常运行?的详细内容,更多请关注代码网其它相关文章!
发表评论