Keep-alive如何与ThreadPoolExecutor一起工作? [英] How does Keep-alive work with ThreadPoolExecutor?

查看:75
本文介绍了Keep-alive如何与ThreadPoolExecutor一起工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

继续问题由我发布,我正在尝试使用 ThreadPoolExecutor 在我的代码库中.即使反复尝试从Java API文档中了解,我仍然无法清楚地理解要在构造函数中传递的keepAliveTime参数背后的功能/目的.希望有人可以通过一些很好的例子向我解释.

In continuation to a question posted by me, I'm trying to use ThreadPoolExecutor in my codebase. Even after repeated attempts to comprehend from Java API doc, I failed to understand clearly the functionality/purpose behind keepAliveTime parameter to be passed in the constructor. Hope somebody can explain me with some good working example.

摘录自Java文档:

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue)

keepAliveTime --当线程数大于内核数时,这是多余的空闲线程在等待新任务之前的最长时间终止.

推荐答案

假设您的核心大小为5,最大大小为15.由于某种原因,您的池变得很忙,并使用了所有15个可用线程.最终,您会耗尽工作量,因此某些线程在完成最终任务时会变得空闲.因此,其中10个线程被允许死亡.

Suppose you have a core size of 5, and a maximum size of 15. For some reason your pool gets busy, and uses all 15 available threads. Eventually you run out of work to do - so some of your threads become idle as they finish their final task. So 10 of those threads are allowed to die.

但是,为避免过快地杀死它们,可以指定保持活动时间.因此,如果将1指定为keepAliveTime值并将TimeUnit.MINUTE指定为unit值,则每个线程在完成执行任务后将等待一分钟,以查看是否还有更多工作要做.如果仍然没有做更多的工作,它将自行完成,直到池中只有5个线程-池的核心".

However, to avoid them being killed off too quickly, you can specify the keep-alive time. So if you specified 1 as the keepAliveTime value and TimeUnit.MINUTE as the unit value, each thread would wait one minute after it had finished executing a task to see if there was more work to do. If it still hadn't been given any more work, it would let itself complete, until there were only 5 threads in the pool - the "core" of the pool.

这篇关于Keep-alive如何与ThreadPoolExecutor一起工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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