ThreadGroup Sample in Java

By: Mashoud Emailed: 1729 times Printed: 2328 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

Thread groups offer a convenient way to manage groups of threads as a unit. This is particularly valuable in situations in which you want to suspend and resume a number of related threads. For example, imagine a program in which one set of threads is used for printing a document, another set is used to display the document on the screen, and another set saves the document to a disk file. If printing is aborted, you will want an easy way to stop all threads related to printing. Thread groups offer this convenience. The following program, which creates two thread groups of two threads each, illustrates this usage:

// Demonstrate thread groups.
class NewThread extends Thread {
boolean suspendFlag;
NewThread(String threadname, ThreadGroup tgOb) {
super(tgOb, threadname);
System.out.println("New thread: " + this);
suspendFlag = false;
start(); // Start the thread
}
// This is the entry point for thread.
public void run() {
try {
for(int i = 5; i > 0; i—) {
System.out.println(getName() + ": " + i);
Thread.sleep(1000);
synchronized(this) {
while(suspendFlag) {
wait();
}
}
}
} catch (Exception e) {
System.out.println("Exception in " + getName());
}
System.out.println(getName() + " exiting.");
}
void mysuspend() {
suspendFlag = true;
}
synchronized void myresume() {
suspendFlag = false;
notify();
}
}
class ThreadGroupDemo {
public static void main(String args[]) {
ThreadGroup groupA = new ThreadGroup("Group A");
ThreadGroup groupB = new ThreadGroup("Group B");
NewThread ob1 = new NewThread("One", groupA);
NewThread ob2 = new NewThread("Two", groupA);
NewThread ob3 = new NewThread("Three", groupB);
NewThread ob4 = new NewThread("Four", groupB);
System.out.println("\\nHere is output from list():");
groupA.list();
groupB.list();
System.out.println();
System.out.println("Suspending Group A");
Thread tga[] = new Thread[groupA.activeCount()];
groupA.enumerate(tga); // get threads in group
for(int i = 0; i < tga.length; i++) {
((NewThread)tga[i]).mysuspend(); // suspend each thread
}
try {
Thread.sleep(4000);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Resuming Group A");
for(int i = 0; i < tga.length; i++) {
((NewThread)tga[i]).myresume(); // resume threads in group}
// wait for threads to finish
try {
System.out.println("Waiting for threads to finish.");
ob1.join();
ob2.join();
ob3.join();
ob4.join();
} catch (Exception e) {
System.out.println("Exception in Main thread");
}
System.out.println("Main thread exiting.");
}
}

Sample output from this program is shown here:

New thread: Thread[One,5,Group A]
New thread: Thread[Two,5,Group A]
New thread: Thread[Three,5,Group B]
New thread: Thread[Four,5,Group B]
Here is output from list():
java.lang.ThreadGroup[name=Group A,maxpri=10]
Thread[One,5,Group A]
Thread[Two,5,Group A]
java.lang.ThreadGroup[name=Group B,maxpri=10]
Thread[Three,5,Group B]
Thread[Four,5,Group B]
Suspending Group A
Three: 5
Four: 5
Three: 4
Four: 4
Three: 3
Four: 3
Three: 2
Four: 2
Resuming Group A
Waiting for threads to finish.
One: 5
Two: 5
Three: 1
Four: 1
One: 4
Two: 4
Three exiting.
Four exiting.
One: 3
Two: 3
One: 2
Two: 2
One: 1
Two: 1
One exiting.
Two exiting.
Main thread exiting.

Inside the program, notice that thread group A is suspended for four seconds. As the output confirms, this causes threads One and Two to pause, but threads Three and Four continue running. After the four seconds, threads One and Two are resumed. Notice how thread group A is suspended and resumed. First, the threads in group A are obtained by calling enumerate( ) on group A. Then, each thread is suspended by iterating through the resulting array. To resume the threads in A, the list is again traversed and each thread is resumed. One last point: this example uses the recommended Java 2 approach to suspending and resuming threads. It does not rely upon the deprecated methods
suspend( )
and resume( ).


Java Home | All Java Tutorials | Latest Java Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(4)


1. View Comment

The following line in the code
((NewThread)tga[i]).myresume(); // resume threads in group}
needs the closing curly bracket placed on next line, rather than in the comment.
Thanks for the code example (and chance to debug:)


View Tutorial          By: Carlos at 2009-11-18 14:34:51
2. View Comment

WHY You are using such huge code for suspending and resuming
.....appart from that we can just use
booean threadActivatedFlag = false;
while(){
initialize all thread..........
start the thread..
add in group...
}
........................
while(threadActivatedFlag )
{
if(threadGroup.activeCount()==0)
threadActivatedFlag = false;
else
Thread.sleep(4000);
}


View Tutorial          By: pavan kurariya at 2010-01-14 00:35:55
3. View Comment

Why not a simple array list of threads?
what makes Thread Group special if the iteration is same as a list?


View Tutorial          By: Ranadheer Machineni at 2011-08-18 12:30:35
4. View Comment

Article from Java Complete Reference

View Tutorial          By: venkatesh at 2013-06-04 01:29:02

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Mashoud
ThreadGroup Sample in Java
Converting Numbers to and from Strings using Java
Using toLowerCase( ) and toUpperCase( ) in Java
How to use regionMatches( ) in Java
startsWith( ) and endsWith( ) in Java
equals( ) Versus == in Java
compareTo( ) in Java
String Conversion and toString() in Java

More Tutorials in Java
Update contents of a file within a jar file
Tomcat and httpd configured in port 8080 and 80
Java File
Java String
Count number of vowels, consonants and digits in a String in Java
Reverse a number in Java
Student marks calculation program in Java
Handling Fractions in Java
Calculate gross salary in Java
Calculate average sale of the week in Java
Vector in Java - Sample Program
MultiLevel Inheritance sample in Java
Multiple Inheritance sample in Java
Java program using Method Overriding
Java program to check if user input is an even number

More Latest News
Most Viewed Articles (in Java )
How to Send SMS using Java Program (full code sample included)
XML and Java - Parsing XML using Java Tutorial
The Basic Structure of a Simple Java program
Method Overriding in Java
Recursion in java
Method Overloading (function overloading) in Java
wait(), notify() and notifyAll() in Java - A tutorial
How to use ArrayList in Java
FileReader and FileWriter example program in Java
Using StringTokenizer in Java
Vector example in Java
Stack example in Java - push(), pop(), empty(), search()
Using One-Dimensional Arrays in Java
Transient vs Volatile modifiers in Java
Count number of vowels, consonants and digits in a String in Java
Most Emailed Articles (in Java)
FileOutputStream - sample program in Java
Palindrome String in Java
SequenceInputStream example program in Java
Student marks calculation program in Java
Multiple Inheritance sample in Java
Java program to check if user input is an even number
Draw a bar chart in Java
Write to a file in Java - Sample Program
cloneable in Java
How to modify the objects using java classes
Java program for changeable wrapper class
How to reverse the elements in a Single dimension array and display the output
How to count the number of digits in any Input number other than negative numbers
Creating Users and Passwords with Tomcat using tomcat-users.xml
Using Parameters in JasperReports