We can see both public void run() and public synchronized void start() are methods of Thread class but we always use thread.start() to invoke the thread rather than using thread.run(). Why? The reason is explained below.
When we invoke a thread using start() method, a new thread stack is created and the run() method starts executing in a new thread stack. But if we call the run() method directly, the new thread stack is not created, rather the run() method executes in current thread stack. The following example clearly tells the difference between calling start() & run() methods.
MyThreadClass.java
MainClass.java
Output:
If we call run() method directly, we can clearly see that the output changes as follows:
Output:
MyThreadClass.java
public class MyThreadClass implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" is running.");
}
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" is running.");
}
}
MainClass.java
public class MainClass {
public static void main(String[] args) {
Thread.currentThread().setName("Main Thread");
System.out.println("This is main thread: "+Thread.currentThread().getName());
MyThreadClass myThread = new MyThreadClass();
Thread t = new Thread(myThread, "My Thread");
t.start();
}
}
public static void main(String[] args) {
Thread.currentThread().setName("Main Thread");
System.out.println("This is main thread: "+Thread.currentThread().getName());
MyThreadClass myThread = new MyThreadClass();
Thread t = new Thread(myThread, "My Thread");
t.start();
}
}
Output:
This is main thread: Main Thread //This is instance of main thread.
My Thread is running. //This is new thread instance.
My Thread is running. //This is new thread instance.
If we call run() method directly, we can clearly see that the output changes as follows:
Output:
This is main thread: Main Thread //This is instance of main thread.
Main Thread is running. //run() is also invoked in main thread stack.
Main Thread is running. //run() is also invoked in main thread stack.
No comments:
Post a Comment