Skip to content

Instantly share code, notes, and snippets.

@ram0973
Last active March 8, 2021 21:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ram0973/76bb87132841a7c0a23ca47ff07c7150 to your computer and use it in GitHub Desktop.
Save ram0973/76bb87132841a7c0a23ca47ff07c7150 to your computer and use it in GitHub Desktop.
Как получить список живых нитей из группы ThreadGroup? Как получить список мертвых нитей из группы ThreadGroup?
package com.examples;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Main {
public static List<Thread> threads = new ArrayList<>();
public static void main(String[] args) throws InterruptedException {
Random random = new Random();
final ThreadGroup group1 = new ThreadGroup("GROUP 1");
for (int i = 1; i <= 100; i++) {
Thread thread = new Thread(group1, "THREAD №" + i) {
@Override
public void run() {
final boolean randomBoolean = random.nextBoolean();
while (!isInterrupted()) {
try {
if (randomBoolean) {
Thread.sleep(random.nextInt(5000));
this.interrupt();
}
} catch (InterruptedException e) {
System.out.println(getName() + " : " +
getThreadGroup().getName() + " прервана");
}
}
}
};
threads.add(thread);
thread.start();
}
Thread.sleep(2500);
List<Thread> runnable = getAllThreads(Thread.State.RUNNABLE, threads);
System.out.printf("Runnable amount: %s%n", runnable.size());
List<Thread> timedWaiting = getAllThreads(Thread.State.TIMED_WAITING, threads);
System.out.printf("Timed waiting amount: %s%n", timedWaiting.size());
List<Thread> terminated = getAllThreads(Thread.State.TERMINATED, threads);
System.out.printf("Terminated amount: %s%n", terminated.size());
if (terminated.size() > 0)
System.out.println(null == terminated.get(0).getThreadGroup()); // TRUE !!!
for (Thread thread : runnable) {
thread.interrupt();
}
}
public static List<Thread> getAllThreads(final Thread.State state, List<Thread> threadList ) {
List<Thread> found = new ArrayList<>();
for (Thread thread : threadList)
if (thread.getState() == state)
found.add(thread);
return found;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment