Java执行器和长寿命线程 [英] Java Executor and Long-lived Threads

查看:80
本文介绍了Java执行器和长寿命线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've inherited some code that uses Executors.newFixedThreadPool(4); to run the 4 long-lived threads that do all the work of the application.

这是推荐的吗?我已阅读实践中的Java并发性而且关于如何管理长期存在的应用程序线程似乎没有太多指导.

Is this recommended? I've read the Java Concurrency in Practice book and there does not seem to be much guidance around how to manage long-lived application threads.

建议和启动整个应用程序整个生命周期的多个线程的建议方法是什么?

What is the recommended way to start and manage several threads that each live for the entire live of the application?

推荐答案

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

You mentioned that code is using Executors, it should be returning an ExecutorService

ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);

ExecutorServiceExecutor,它提供了管理终止的方法以及可以生成Future来跟踪一个或多个异步任务的进度的方法.

ExecutorService is an Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

只要返回的ExecutorService正在执行正常关机,就不会有问题.

As long as returned ExecutorService is performing graceful shutdown there should not be an issue.

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

You can check that your code is doing shutodwn by finding following in your code:

// 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();

干杯!

这篇关于Java执行器和长寿命线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆