beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
    • Learn jQuery
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

Can we start a Thread twice in Java?

By Chaitanya Singh | Filed Under: Multithreading

Can we start a thread twice in Java? The answer is no, once a thread is started, it can never be started again. Doing so will throw an IllegalThreadStateException. Lets have a look at the below code:

public class ThreadTwiceExample implements Runnable {
   @Override
   public void run(){  
	Thread t = Thread.currentThread();
        System.out.println(t.getName()+" is executing.");
		    
   }  
   public static void main(String args[]){  
	Thread th1 = new Thread(new ThreadTwiceExample(), "th1"); 
	th1.start();  
	th1.start();  
   } 
}

Output:

Exception in thread "main" th1 is executing.
java.lang.IllegalThreadStateException

As you observe the first call to start() resulted in execution of run() method, however the exception got thrown when we tried to call the start() second time.

Comments

  1. juvin says

    July 17, 2015 at 2:23 AM

    hello,
    you are doing a very good job in clarifying the java basics for the newbies …
    please keep doing it more and more on more topics.. :) (greedy me :p )

    i have a doubt.
    the same thread cannot be started multiple times. what if i instantiate the class again and then start it again?
    ti = new ThreadclassName();
    ti.start;
    t2= new ThreadclassName();
    t2.start();

    is this possible?

    Reply
    • Neeraj says

      July 27, 2015 at 2:24 PM

      Hi Juvin,
      It is possible if we instantiate same class again and invoke run method by start, the program will compile successful.Now we are not running same thread.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Multithreading

  • Multithreading
  • Process vs Thread
  • Thread Life Cycle
  • Daemon thread
  • thread join()
  • Why call start()
  • Thread starting twice?
  • Multithreading Interview Q

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2022 BeginnersBook . Privacy Policy . Sitemap