It is possible that we can group multiple threads in a single object. Here , we can suspend, resume or interrupt group of threads by a single method call.
Now suspend(), resume() and stop() methods are deprecated.
Java thread group is implemented by java.lang.ThreadGroup class.
Let's see a code to group multiple threads.
Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is the class that implements Runnable interface and "one", "two" and "three" are the thread names.
Now we can interrupt all threads by a single line of code only.
Thread.currentThread().getThreadGroup().interrupt();
public class ThreadGroupExample implements Runnable{ public void run(){ System.out.println(Thread.currentThread().getName()); } classTestThreadGroup { public static void main(String[] args) { ThreadGroupExample obj = new ThreadGroupExample(); ThreadGroup tg = new ThreadGroup("Parent ThreadGroup"); Thread t1 = new Thread(tg, obj,"one"); t1.start(); Thread t2 = new Thread(tg, obj,"two"); t2.start(); Thread t3 = new Thread(tg, obj,"three"); t3.start(); System.out.println("Thread Group Name: "+tg1.getName()); tg.list(); } } }
Output
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
Thread[one,5,Parent ThreadGroup]
Thread[two,5,Parent ThreadGroup]
Thread[three,5,Parent ThreadGroup]
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc