Can we override start method of thread class in java?

Answer: Yes, we can override start() method of thread in Java, the same way we override any other methods. for example, In below, custom thread class MyThread, both start() method and run() method have been overridden. When we create an object of custom thread and call start() method, run() will be automatically called. You may read how to create thread in java programming.

class MyThread extends Thread {
	@Override
	public void start() {

		System.out.println("Initializing library....");
		// do something e.g. some required library initialization
		System.out.println("Starting a new thread.....");
		super.start();
	}

	@Override
	public void run() {
		// do something in a new thread if called by super.start()
		System.out.println("Processing in new thread.....");
	}
}

public class Sample {

	public static void main(String[] args) {

		MyThread t = new MyThread();
		t.start();
	}
}

Output:
Initializing library….
Starting a new thread…..
Processing in new thread…..

NOTE:

  • We must call super.start() to create a new thread and have run() called in that new thread.
  • If you call run ( ) method directly from within your start ( ) (or any other method), it is executed in the actual thread as a normal method, not in a new thread.

NOTES:
We may raise a question that why do we need to override start() method in Java thread?  Answer is simple, we might want to initialize something e.g our own library or may want  to call some methods for some initial task before starting a new thread. In this situation, we have to override start() method.

Related Posts