Reputation: 582
Here is my custom thread class
public class ThreadEngine extends Thread{
private int processid;
public int getProcessid() {
return processid;
}
public void setProcessid(int processid) {
this.processid = processid;
}
public void run(){
int count=0;
for(Thread t:Thread.getAllStackTraces().keySet()){
ThreadEngine t1=(ThreadEngine)t;
int processtid=t1.getProcessid();
if(t.getState()==Thread.State.RUNNABLE)count++;
}
}
}
Here i am trying to typecast the currently running threads into my custom thread class but i am getting cast exception.
I want to get processid's of currently running threads.How is it possible?
Upvotes: 1
Views: 1296
Reputation: 1071
Couple of easy ways to handle this. Full working code on online java ide
What are you trying to achieve? The run() method always runs in the thread were the instance is ThreadEngine.
So you could simply use getProcessid()
in the run() method to access the process id.
At any other place, if you want to access the current thread, you could simply use
Thread.currentThread()
that returns the current thread.
If you are looking for any thread instead of just current thread, then you should make sure if it is of the current instance type using the instanceof
keyword.
I have attached the working code in codiva java online compiler ide.
Upvotes: 1
Reputation: 140318
You are making the assumption that the only threads which exist in your JVM are the ones you have started. This isn't the case, as the following snippet illustrates when run on ideone:
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
for (Thread t : Thread.getAllStackTraces().keySet()) {
System.out.println(t.getClass() + " " + t.getName());
}
}
}
Output:
class java.lang.ref.Finalizer$FinalizerThread Finalizer
class java.lang.Thread Signal Dispatcher
class java.lang.ref.Reference$ReferenceHandler Reference Handler
class java.lang.Thread main
Despite the fact that the code creates no threads explicitly, there are 4 threads shown. So if your code does create threads, you should expect some extra threads in addition to yours.
As such, you need to check if the thread you are currently processing actually is an instance of the expected class before casting:
for(Thread t:Thread.getAllStackTraces().keySet()){
if (t instanceof ThreadEngine) {
ThreadEngine t1=(ThreadEngine)t;
// ...
}
}
This will simply ignore other types of thread.
Upvotes: 1
Reputation: 4588
Simplest way is probably if the master thread which creates your ThreadEngine instances keeps a reference of each instance within a collection. Just iterate over this collection for calling getProcessid().
But: If you only want to count your running instances you do not need the processId, isn't it?
Upvotes: 0