CodesJava

Easy learning with example program codes

Can we start a thread twice?


No, A thread can never be started again after starting once. It will throw IllegalThreadStateException.

Example:

ThreadExample.java

/**
 * This program is used to show that we can not start
 * a thread which is already started.
 * @author codesjava
 */
class Test extends Thread{
	public void run(){
		System.out.println("thread started.");
	}
}
 
public class ThreadExample {
	public static void main(String args[]){
		//creating thread.
		Test thrd = new Test();
 
		//start the thread.
		thrd.start();
 
		//again start the thread which is already started.
		//IllegalThreadStateException here.
		thrd.start();
	}
}

Output:

Exception in thread "main" thread started.
java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at com.codesjava.business.ThreadExample.main
(ThreadExample.java:24)

Download this example.
 
Next Topic: Can we call run method directly?
Previous Topic: Daemon thread in java with example.

Related Topics:

Please follow and like us:
Posted in Java   

Core Java Tutorial



Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki