What is difference between start and run in Java Thread?

Answer includes the difference between start and run
Describing the interview question, difference between run and start method in Java multithreading with example. But, also note that this question can also be asked as  below

“if start() method eventually call run() method in a thread then why don’t we call run() method directly?”

Answer:

Thread.start() method creates a new thread and call the code block written inside run() method  on newly created thread while calling run() method does not create a new thread but executes the code in run() method on current  thread itself like a normal method call.

Here is sample and output that clearly state difference.

Thread – start() method:

public class StartSample implements Runnable  {

	/**
	 * thread start() method sample
	 */
	public static void main(String[] args) {	
		
		Thread t = new Thread( new StartSample());
		t.start(); // will create a new thread and call run() method internally.

	}

	@Override
	public void run() {
		
		System.out.println("This method is executed by : " + Thread.currentThread().getName());
		
	}
}

Output : This method is executed by : Thread-0

Thread – run() method:

public class RunSample implements Runnable{
	/**
	 * thread run() method sample
	 */
	public static void main(String[] args) {	
		
		Thread t = new Thread( new StartSample());
		t.run(); // It will be called as a normal method of class RunSample by main thread

	}

	@Override
	public void run() {
		
		System.out.println("This method is executed by : " + Thread.currentThread().getName());
		
	}
}
Output : This method is executed by : main

Related Posts