ThreadGroups in Java Programming
Previous | Home | Next |
java.lang ThreadGroup class is used to make a group of threads.ThreadGroup is used to represent more than one thread as a single thread. We can start or suspend all related threads within a group with a single method call.
We can make thread group using one of following : public Thread(ThreadGroup group, Runnable target) public Thread(ThreadGroup group, String name) public Thread(ThreadGroup group, Runnable target, String name) eg. ThreadGroup tg = new ThreadGroup("Group of Threads"); Thread myThread = new Thread(tg, new R4R()); We can use getThreadGroup() method to get thread groups: theGroup = td.getThreadGroup(); The ThreadGroup class has two constructors. ThreadGroup(String name) ThreadGroup(ThreadGroup parent, String name)
public class ThreadGroupTest{ public static void main(String[] args){ ThreadGroup tg = new ThreadGroup("test"); Thread t1 = new Thread(tg, new T(), "t1"); Thread t2 = new Thread(tg, new T(), "t2"); t1.start(); t2.start(); } } class R4R implements Runnable{ public void run(){ for(int i = 1; i < 50; i++){ System.out.println(i); } } }
Previous | Home | Next |