Finding Active Threads

4

I have the following problem, where I have a for() that opens 17 threads and need to retrieve, in another thread (18th) the active threads I opened earlier and check which ones are still active. I took a look around the internet, but I did not find any plausible solution to my problem.

What would be the best solution to recover the active threads I opened earlier?

Follow the Code:

for(int i = 1; i <= 500; i+=30){
  Runnable r = new Async(empresa,i,30);
  Thread t = new Thread(r);             
  t.start();
}
    
asked by anonymous 20.04.2016 / 19:05

1 answer

5

Well, I found the solution by assigning each created thread to an arrayList, where later I check if it is active, picking up each thread from the list.

The code looks like this:

List<Thread> threadArray = new ArrayList<Thread>();

for(int i = 1; i <= 500; i+=30){
    Runnable r = new Async(empresa,i,30);
    Thread t = new Thread(r);               
    threadArray.add(t);
    t.start();      
}

Subsequently on the other Thread:

for (Thread t : threadArray) {                  
    System.out.println("Ativo: "+t.isAlive());
}
    
20.04.2016 / 20:08