Member-only story
Java Multithreading Madness: Get Ready to Rock Your Threads!
class MyThread extends Thread {
public void run() {
System.out.println("MyThread running");
}
}
public class Main {
public static void main(String args[]) {
MyThread myThread = new MyThread();
myThread.start();
}
}
1. What is the difference between calling myThread.start()
and myThread.run()
in Java?
The difference between myThread.start()
and myThread.run()
is that start()
actually creates a new thread and starts its execution, while run()
simply executes the code in the current thread.
When you call myThread.start()
, the Java Virtual Machine (JVM) creates a new thread and calls the run()
method of that thread in a separate execution path. This allows the code in the run()
method to execute concurrently with the code in the main thread.
On the other hand, when you call myThread.run()
, the run()
method is executed in the current thread, which is usually the main thread. This does not create a new thread, so the code in the run()
method is executed sequentially with the code in the main thread.
Therefore, if you want to run your thread concurrently with the main thread, you should call start()
. If you call run()
, the code in the thread will execute…