Site icon TechVidvan

Can we start a Thread twice in Java

Multithreading is a powerful technique in Java that enables concurrent execution of multiple tasks within a single program. The thread is the foundation for multithreading, providing a means to perform tasks simultaneously while leveraging the full potential of today’s processors with more than one core. The starting() method, the fundamental building block for initiating Java’s threads, is at the heart of thread execution.

Thread.start()

There is no way of starting a new thread in Java without first running the thread class start() since the thread class start() is responsible for registering the thread with the thread scheduler and doing all other necessary tasks.

It initiates a new thread, transfers it from the “New” state to the “Runnable” state, and causes its target run() to be executed once the thread has a chance to do so.

The Thread’s target run() will be called once it has a chance to run.

Overriding of the strat()

When we’re overriding the start method, then start() will be performed as in a normal method call.

Example Program:

public class TechvidvanThreadDemo{
    public static void main(String[] args) {
      	//creating a thread
    	MyThread t=new MyThread();
    	t.start();
    }
}
class MyThread extends Thread{
    public void start(){
 	//overriding the strat()
   	 System.out.println("TechVidvan-start method");
    }
    public void run(){
    	System.out.println("TechVidvan-run method");
    }
}

Output:

TechVidvan-start method

When the t.start() is called in the TechvidvanThreadDemo class, the overridden start() method of MyThread gets executed, but it doesn’t initiate the actual thread execution as the original start() method would have. The run() method is never executed in this case. It is crucial to avoid overriding the start() method in the Thread subclass because the start() method is responsible for creating a new thread, setting up the thread’s context, and then invoking the run() method in the new thread.

Start a thread twice in Java

The Thread class maintains an internal state that changes when the thread is started and runs to completion. Once a thread has been started and completed its execution or terminated, it cannot be restarted. The thread object is no longer in a state that enables it to be started again. An IllegalThreadStateException will occur when attempting to start a thread that has already been started.

Example Program:

public class Main {
    public static void main(String[] args) {
    	MyRunnable r=new MyRunnable();
        Thread t=new Thread(r);
        // Starting the thread for the first time	
        t.start();
        // Trying to start the same thread again
    	try{
        	t.start();
    	}
    	catch (IllegalThreadStateException e){
        	System.out.println("IllegalThreadStateException:Thread already started");
    	}
    }
}
class MyRunnable implements Runnable{
    public void run(){
        System.out.println("TechVidvan-Thread is running");
    }
}

Output:

TechVidvan-Thread is running

IllegalThreadStateException: Thread already started.

As expected, the thread is started the first time successfully, and it executes the run() method, printing “TechVidvan-Thread is running” to the console. However, when you try to start the same thread again by calling t.start() a second time, it throws an IllegalThreadStateException.The reason for this exception is that once a thread has been started and completed its execution, it cannot be restarted using the start() method. The thread’s internal state changes from “New” to “Runnable” and eventually to “Terminated” after the run() method completes execution, and it cannot be started again.

Summary

In summary, starting a thread twice is not allowed in Java, and attempting to do so will result in an IllegalThreadStateException. Threads are meant to be executed only once, and if you need to perform a task multiple times or concurrently, create new threads with new Runnable instances to maintain proper thread management and avoid exceptions and concurrency issues.

Exit mobile version