有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

多线程Java ThreadPoolExecutor关闭特定线程?

我正在编写我的系统编程课程作业(使用线程)

我的活动类实现runnable,我有另一个类,它的执行器使用:ThreadPoolExecutor e = (ThreadPoolExecutor) Executors.newFixedThreadPool(number);执行该runnable

我有几个线程在该线程池中同时运行。我的问题如下:我可以选择知道一个线程何时完成了它的工作,关于它需要做什么,我如何关闭这个线程,以及-只有-这个线程,而不是整个执行器


共 (2) 个答案

  1. # 1 楼答案

    ThreadPoolExecutor负责管理其线程,您无法访问它们,除非通过一些可能会破坏执行器的丑陋的黑客攻击。您应该使用API提供的配置选项,例如setKeepAliveTime或接受keepAliveTime的构造函数。将该值设置为零,您将自动获得所需的行为

  2. # 2 楼答案

    如果我理解正确,你想要的是^{}而不是newFixedThreadPool

    来自Java文档

    Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will be created and added to the pool. Threads that have not been used for sixty seconds are terminated and removed from the cache. Thus, a pool that remains idle for long enough will not consume any resources. Note that pools with similar properties but different details (for example, timeout parameters) may be created using ThreadPoolExecutor constructors.