Home | | Web Programming | Thread, ThreadGroup, and Runnable - java.lang

Chapter: Java The Complete Reference : The Java Library : Exploring java.lang

Thread, ThreadGroup, and Runnable - java.lang

The Runnable interface and the Thread and ThreadGroup classes support multithreaded programming. Each is examined next.

Thread, ThreadGroup, and Runnable

 

The Runnable interface and the Thread and ThreadGroup classes support multithreaded programming. Each is examined next.

The Runnable Interface

 

The Runnable interface must be implemented by any class that will initiate a separate thread of execution. Runnable only defines one abstract method, called run( ), which is the entry point to the thread. It is defined like this:

 

void run( )

 

Threads that you create must implement this method.

Thread

 

Thread creates a new thread of execution. It implements Runnable and defines the following commonly used constructors:

 

Thread( )

 

Thread(Runnable threadOb)

 

Thread(Runnable threadOb, String threadName)

 

Thread(String threadName)

 

Thread(ThreadGroup groupOb, Runnable threadOb)

 

Thread(ThreadGroup groupOb, Runnable threadOb, String threadName)

 

Thread(ThreadGroup groupOb, String threadName)

 

threadOb is an instance of a class that implements the Runnable interface and defines where execution of the thread will begin. The name of the thread is specified by threadName. When a name is not specified, one is created by the Java Virtual Machine. groupOb specifies the thread group to which the new thread will belong. When no thread group is specified, the new thread belongs to the same group as the parent thread.

The following constants are defined by Thread:

 

MAX_PRIORITY

 

MIN_PRIORITY

 

NORM_PRIORITY

 

As expected, these constants specify the maximum, minimum, and default thread priorities. The methods defined by Thread are shown in Table 17-18. In early versions of Java,

 

Thread also included the methods stop( ), suspend( ), and resume( ). However, as explained in Chapter 11, these were deprecated because they were inherently unstable. Also deprecated are countStackFrames( ), because it calls suspend( ), and destroy( ), because it can cause deadlock.






ThreadGroup

 

ThreadGroup creates a group of threads. It defines these two constructors:

 

ThreadGroup(String groupName) ThreadGroup(ThreadGroup parentOb, String groupName)

 

For both forms, groupName specifies the name of the thread group. The first version creates a new group that has the current thread as its parent. In the second form, the parent is specified by parentOb. The non-deprecated methods defined by ThreadGroup are shown in Table 17-19.



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.");

 

}

 

synchronized 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 (the precise output you see may differ):

 

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 approach to suspending and resuming threads. It does not rely upon the deprecated methods suspend( ) and resume( ).

 

ThreadLocal and InheritableThreadLocal

 

Java defines two additional thread-related classes in java.lang:

 

        ThreadLocal  Used to create thread local variables. Each thread will have its own copy of a thread local variable.

        InheritableThreadLocal   Creates thread local variables that may be inherited.

 




Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Java The Complete Reference : The Java Library : Exploring java.lang : Thread, ThreadGroup, and Runnable - java.lang |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.