Saturday, 13 July 2019

Thread Creation in Java

Thread Can be defined as the smallest execution part in with the process(an instance of the program running in computer).

We can see how to create a thread and rules around it in the coming blogs.
Thread Can be created using the below two approaches.

1. Implementing the runnable Interface.
2. Extending the Thread class.

Most of us if we tell there are two ways the next question to be asked his what is the best approach.
Many developers including me thinks that class should be extended when they are being enhanced or modified in someway.
So if will not be overide any of the threads other methods, it is probably best simply to implement the runnable.

1. Implementing the runnable Interface.

package com.searchendeca.thread.sample;

 class ThreadDemoImplements implements Runnable {

Thread t;
ThreadDemoImplements(){
t= new Thread(this,"MY Threadd");
t.start();
}

@Override
public void run() {
for(int n = 5; n > 0; n--) {
System.out.println("*********"+n);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}

}

}
 class calling {

public static void main(String args[]) {
new ThreadDemoImplements();
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.");
}

 }

 2. Extending the thread class.

 package com.searchendeca.thread.sample;

 class ThreadDemoExtends extends Thread {

ThreadDemoExtends(){
super("Demo Thread");
start();
}


public void run() {
for(int n = 5; n > 0; n--) {
System.out.println("*********"+n);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Main thread interrupted");
}
}

}

}
 class callingExtends {

public static void main(String args[]) {
new ThreadDemoExtends();
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.");
}

 }

The difference between the thread creation using Implementing the runnable and  extending the thread class is no need to create the Instance in extending the thread class.

No comments:
Write comments