gpt4 book ai didi

java - 当线程死亡时执行操作

转载 作者:太空宇宙 更新时间:2023-11-04 06:51:40 25 4
gpt4 key购买 nike

我正在使用ThreadPoolExecutor,并且需要将workerID与每个线程相关联,因此当线程终止时,应该删除该ID,并且在创建新线程时应该使用该ID。但我如何确保线程死亡。并执行一些操作。

不能依赖 run 方法完成,因为 keepAliveTime 为 15 分钟。

有什么方法可以确保这一点吗?

ThreadFactory newThread 方法是这样的:

public Thread newThread(Runnable r)
{
Thread thread = new Thread(group, r, (new StringBuilder()).append(namePrefix).append(threadNumber.getAndIncrement()).toString(), 0L);
if(thread.isDaemon())
{
thread.setDaemon(false);
}

thread.setName((new StringBuilder()).append("Thread name : ").append(name).append(" WorkerId : ").append(getNextWorkerID());
return thread;
}

getNextWorkerID 返回 newxtWorkerID。

最佳答案

延长 ThreadPoolExecutor 怎么样?具有保留 Map<Runnable, String> 的实现值为workerID?您可以覆盖 afterExecute(Runnable, Throwable)并从Map中删除workerID在这个方法中。

关于java - 当线程死亡时执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23238384/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com