gpt4 book ai didi

java - 查找线程池内 Activity 线程的名称: ExecutorService in java

转载 作者:行者123 更新时间:2023-12-01 06:03:40 25 4
gpt4 key购买 nike

所以我正在运行一个执行程序服务,我想知道所有当前 Activity/空闲线程的名称或线程ID。

ExecutorService service = Executors.newCachedThreadPool(ThreadFactory threadFactory)

我不需要知道计数,但需要知道执行程序服务中所有 Activity 线程的实际名称/ID。我需要以任何方式识别线程,因为我计划使用适当的命名约定来实现我自己的 ThreadFactory。

例如,如果我的 Activity 线程是 T0、T1、T3,我的 threadfactory 会将下一个线程命名为 T2。但我找不到一种方法来获取有关 Activity 线程的信息。我怎样才能做到这一点?

PS:任何其他方法也将不胜感激。例如,假设我可以使用名称从 T0 到 T50 的线程。我只是希望当前的 threadfactory 分配从 T0 到 T50 的任何名称,以便具有相同名称的线程当前不处于 Activity 状态或空闲状态。

最佳答案

我可以自由地为您创建一个我本来会做的事情的样本。但我无法真正测试它:

public class CachingThreadFactory implements ThreadFactory{
// amount of active threads at max
private static final int THREAD_POOL_MAX_SIZE = 8;

// interval in milliseconds of the clean up task
private static final int CLEAN_UP_INTERVAL = 2000;

// the actual cache
private final Thread[] cachedThreads = new Thread[THREAD_POOL_MAX_SIZE];

// clean up task definition
{
new Timer().scheduleAtFixedRate(new CleanUpTask(), 0, CLEAN_UP_INTERVAL);
}

@Override
public synchronized Thread newThread(Runnable r){
for(int i = 0; i < cachedThreads.length; i++){
if(cachedThreads[i] == null){
return cachedThreads[i] = new Thread(r, "T" + i);
}
}
return null;
}

private final class CleanUpTask extends TimerTask{
@Override
public void run(){
synchronized(CachingThreadFactory.this){
for(int i = 0; i < cachedThreads.length; i++){
final Thread thread = cachedThreads[i];
if(thread != null && !thread.isAlive()){
cachedThreads[i] = null; // unset
}
}
}
}
}
}

该工厂将其创建的每个线程缓存在数组中。然后它异步运行 cleanUpTask 来检查数组中的线程(如果有)是否仍然 Activity 。如果没有,它们将被删除。

newThread 方法遍历缓存,查找尚未获取的索引,然后使用该索引创建该Thread 的名称。如果没有空闲位置,则返回 null

这个类可能是线程安全的。但我还没有真正测试过。 synchronized 语句应该防止 cleanUp-Task 和 newThread 方法之间的干扰。但任何其他行为都可能扰乱整个事情。

关于java - 查找线程池内 Activity 线程的名称: ExecutorService in java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50620696/

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