THREAD CLASS

Implementing thread class :-
The easiest way to create a thread is to create a class that implements the Runnable
interface. Runnable abstracts a unit of executable code. You can construct a thread on
any object that implements Runnable. To implement Runnable, a class need only
implement a single method called run( ), which is declared like this:
o public void run( )
Inside run( ), you will define the code that constitutes the new thread. It is important to
understand that run( ) can call other methods, use other classes, and declare variables,
just like the main thread can. The only difference is that run( ) establishes the entry point
for another, concurrent thread of execution within your program. This thread will end
when run( ) returns.
After you create a class that implements Runnable, you will instantiate an object of type
Thread from within that class. Thread defines several constructors. The one that we will
use is shown here:
o Thread(Runnable threadOb, String threadName)
In this constructor, threadOb is an instance of a class that implements the
Runnableinterface. This defines where execution of the thread will begin. The name of
the new thread is specified by threadName.
After the new thread is created, it will not start running until you call its start( )
method, which is declared within Thread. In essence, start( ) executes a call to run( ).
The start( ) method is shown here:
o void start( )

Extending thread class :-
The second way to create a thread is to create a new class that extends Thread, and then to
create an instance of that class. The extending class must override the run( ) method, which is
the entry point for the new thread. It must also call start( ) to begin execution of the new thread.
Here is the preceding program rewritten to extend Thread

// Create a second thread by extending Thread
class NewThread extends Thread {
NewThread() {
// Create a new, second thread
super("Demo Thread");
System.out.println("Child thread: " + this);
start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
class ExtendThread {
public static void main(String args[]) {
new NewThread(); // create a new
thread try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " +
i); Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}

Posted on by