Java 执行器和长寿命线程

2024-05-13

我继承了一些使用 Executors.newFixedThreadPool(4); 的代码运行 4 个长寿命线程来完成应用程序的所有工作。

这是推荐的吗?我读过Java 并发实践 https://rads.stackoverflow.com/amzn/click/com/0321349601书上似乎没有太多关于如何管理长期应用程序线程的指导。

启动和管理多个线程(每个线程在应用程序的整个生命周期中都处于活动状态)的推荐方法是什么?


您提到代码正在使用Executors,它应该返回一个ExecutorService

ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);

ExecutorService is an Executor它提供了管理终止的方法以及可以生成 Future 来跟踪一个或多个异步任务进度的方法。

只要回来了ExecutorService正在执行正常关闭,应该不会有问题。

您可以通过在代码中查找以下内容来检查代码是否正在关闭:

// This will make the executor accept no new threads
// and finish all existing threads in the queue
executor.shutdown();

// Wait until all threads are finish
executor.awaitTermination();

干杯!

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

Java 执行器和长寿命线程 的相关文章

随机推荐