Difference between start() and run() in java ?
Apart of multi threading concept in java we have start() and run() methods.
start(): If we use start() method, a new thread will be created which is responsible for the execution of run() method.
run(): If we use run() method, new thread won't be created and run() method will be executed just like a normal call by main thread.
Program using start() method:
public class ThreadDemo extends Thread {
public void run() {
for (int i = 0; i <= 5; i++) { //executed by child thread
System.out.print("Child Thread "); //executed by child thread
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
//here main thread starts
ThreadDemo td = new ThreadDemo(); //Thread Instantiation //main thread created child thread object
td.start(); //Starting of a thread //here child thread starts
for (int i = 0; i <= 5; i++) {
Thread.sleep(1000);
System.out.print("Main Thread "); //executed by main thread
}
}
}
Output:
Child Thread Child Thread Main Thread Child Thread Main Thread Main Thread Child Thread Child Thread Main Thread Child Thread Main Thread Main Thread
If we observe above program we have used start() method.Whenever start() is used where a thread is created and we have other thread is main thread.So there 2 threads in executing a program and we will get different outputs every time you run the program.
Program using run() method:
public class ThreadDemo extends Thread {
public void run() {
for (int i = 0; i <= 5; i++) { //executed by main thread
System.out.print("Child Thread "); //executed by main thread
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws InterruptedException {
//here main thread starts
ThreadDemo td = new ThreadDemo();
td.run(); //no thread will be created
for (int i = 0; i <= 5; i++) {
Thread.sleep(1000);
System.out.print("Main Thread "); //executed by main thread
}
}
}
Output:
Child Thread Child Thread Child Thread Child Thread Child Thread Child Thread Main Thread Main Thread Main Thread Main Thread Main Thread Main Thread
If we observe above program we have used run() method.Whenever run() is used no thread is created and we have only one thread
i.e., main thread.So there is 1 thread in executing a program and we will get constant output every time you run the program.
i.e., run() method will be invoked like a normal method only.
Please comment below to feedback or ask questions.
No comments:
Post a Comment
Please comment below to feedback or ask questions.