Based
on the functionality we can group threads as a single unit which is nothing but
ThreadGroup. ThreadGroup provides a convenient way to perform common operations
for all the Threads belonging to a particular Group. We can create a
ThreadGroup by using the following constructor.
§ ThreadGroup g = new ThreadGroup(String
groupName);
We
can attach a thread to a ThreadGroup by using the following constructor Thread
class.
§ Thread t = new Thread(ThreadGroup g,String
ThreadName);
Example –
public class
ThreadGroup1 implements Runnable{
@Override
public void
run() {
System.out.println(Thread.currentThread().getName()+", "+Thread.currentThread().getPriority()+", "+Thread.currentThread().getThreadGroup());
}
public static void
main(String[] args) {
ThreadGroup1
group
= new ThreadGroup1();
ThreadGroup
tg = new
ThreadGroup("Groupthread");
Thread t1 = new
Thread(tg,group,"t1");
t1.start();
Thread t2 = new
Thread(tg,group,"t2");
t2.setPriority(10);
t2.start();
}
}
Output –
t1, 5, java.lang.ThreadGroup[name=Groupthread,maxpri=10]
t2, 10,
java.lang.ThreadGroup[name=Groupthread,maxpri=10]
Example –
public class
ThreadGroup1 extends Thread{
@Override
public
String toString() {
return "ThreadGroup1["+getName()+",
"+getPriority()+", "+getThreadGroup()+"]";
}
public static void
main(String[] args) {
Thread t1 = new
Thread();
System.out.println(t1);
Thread t2 = new
Thread("CMP");
System.out.println(t2);
Thread t3 = Thread.currentThread();
System.out.println(t3);
t3.setPriority(9);
System.out.println(t3);
Thread t4 = new
Thread();
System.out.println(t4);
}
}
Output –
Thread[Thread-0,5,main]
Thread[CMP,5,main]
Thread[main,5,main]
Thread[main,9,main]
Thread[Thread-1,9,main]
No comments:
Post a Comment