In Java, a user defined thread can be created to implement the Runnable interface. The Runnable interface has only one method run() that you must have to implement in your class, that you want to create as thread. The run() is the method in which that code is written, which is counted as thread task.
The content of the run() method will be counted as thread portion, but the method written outside the Run() counts as part of the main thread. Both the new thread and main thread can run concurrently. The thread terminates· with the termination of run method. Control is returned to the caller method of the run method, or can say from where it starts. The run() method should not be called directly, the start() method of thread class is called, and that is responsible to call run() for the corresponding thread.
Another way to create a thread is to inherit the Thread class. Thread class has a number of methods. Few of them are static and few are non-static. As per the need you can override non-static methods. But run() method must override, because it defines new thread functionality.
Extending Thread
A new thread is created by creating a new class that extends Thread, and then create an instance of that class. The extending class must override the method run(), which is the entry point of the new thread (user defined). To begin the execution of the new thread, it must call start() method. Inside the run() method, you’ll write the code, which is considered as the functionality of the thread. The run() method can call other method of the same class or other class using their objects. It is an entry point of the thread. As the run() method returns (exit or terminate) the thread ends.
Example:
class NewThreadDemo extends Thread {
public NewThreadDemo() {
super(“User Define Thread”);
System.out.println(“New userdefined child thread created “ + this);
start();
}
public void run() {
try {
for(int i = 1; i <=10; i++) {
System.out.println(“UserDefined Child Thread: “ + i);
Thread.sleep(500);
}
}
catch (InterruptedException e) {
System.out.println(“UseDefine Child interrupted.”);
}
System.out.println(“Exiting UserDeinfed child thread.”);
}
}
class ThreadDemo {
public static void main(String args[]) {
new NewThreadDemo();
try {
for(int i = 1; i <10; i++) {
System.out.println(“Main Thread: “ + i);
Thread.sleep(500);
}
}
catch (InterruptedException e) {
System.out.println(“Main thread interrupted.”);
}
System.out.println(“Main thread exiting.”);
}
}
There are two output of the same thread code. Because it is not always sure that a thread executes in the same manner. The output can be same or vary every time. The super() inside the NewThreadDemo constructor invokes the following form of Thread constructor:
public Thread(String thread_Name)