[英]Get number of active threads in java
I have a class (extends Thread
) of which I am running multiple threads. 我有一个正在运行多个线程的类(扩展
Thread
)。
Here is the class: 这是课程:
public class Abc extends Thread{
private String key;
public void run(){}
}
Now, I want to know how many active threads are there of this class based on value of key
. 现在,我想根据
key
值知道这个类有多少个活动线程。
eg. 例如。 I set the value of key as "X" in 10 threads and "Y" in 15. I want to create a map:
我在10个线程中将key的值设置为“ X”,在15个线程中将key的值设置为“ Y”。我想创建一个映射:
map<String, int> :: {"X"=10, "Y"=15}
How can I do that? 我怎样才能做到这一点?
EDIT: 编辑:
This Map<>
will be stored in the Execute
class, which is creating the threads. 该
Map<>
将存储在正在创建线程的Execute
类中。 It has nothing to do with Abc
. 它与
Abc
无关。
You can increment a counter when the task starts and decrement it when it finishes. 您可以在任务开始时增加计数器,并在任务完成时减少计数器。
Something like 就像是
public void run() {
AtomicInteger counter = counterMap.computeIfAbsent(key, k -> new AtomicInteger());
counter.incrementAndGet();
try {
doRun();
} finally {
counter.getAndDecrement();
}
}
将您的key
静态,以便它将其值保留在线程之间。
You can do something like this: 您可以执行以下操作:
static HashMap<String, Integer> threadsCount = new HashMap<String, Integer>();
String key;
public Abc(String key) {
this.key = key;
synchronized (threadsCount) {
if (threadsCount.containsKey(key)) {
threadsCount.put(key, threadsCount.get(key) + 1);
} else {
threadsCount.put(key, 1);
}
}
}
and decrement the count when a thread finishes: 并在线程结束时减少计数:
@Override
public void run() {
....
synchronized (threadsCount) {
if (threadsCount.containsKey(this.key)) {
threadsCount.put(key, threadsCount.get(this.key) - 1);
}
}
}
@vish4071, based on your comment, I think that a better solution for your use case will be this: @ vish4071,根据您的评论,我认为针对您的用例的更好解决方案是:
public class Abc extends Thread {
String key;
public Abc(String key) {
this.key = key;
}
public String getKey(){
return key;
}
....
}
And to get the count: 并获得计数:
HashMap<String, Integer> threadsCount = new HashMap<String, Integer>();
for (Thread t : Thread.getAllStackTraces().keySet()) {
if (t instanceof Abc) {
if (t.getState() != Thread.State.TERMINATED) {
String key = ((Abc)t).getKey();
if (threadsCount.containsKey(key)) {
threadsCount.put(key, threadsCount.get(key) + 1);
} else {
threadsCount.put(key, 1);
}
}
}
}
public class Abc extends Thread{
private static Map<String, Integer> map = new ConcurrentHashMap<>();
private String key;
public void run(){
synchronized (key) {
Integer current = map.get(key);
if(null == current) {
map.put(key, 1);
} else {
map.put(key, current +1);
}
}
//Run execution code here.
synchronized (key) {
Integer current = map.get(key);
map.put(key, current -1);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.