• August 29, 2014
  • Core Java
  • Comments Off on Can we start a thread twice?

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 javawithease
 */
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.javawithease.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:

Multithreading in java.
Thread life cycle in java.
Way of creating thread in java.
Commonly used methods of Thread class.
Thread scheduling in java with example.
Thread priority in java with example.
Naming a thread in java with example.
Joining a thread in java with example.
Daemon thread in java with example.
Can we start a thread twice?
Can we call run method directly?
Difference between Thread.yield() and Thread.sleep() methods.
Deadlock in java with example.
Starvation in java with example.
Inter-thread communication in java with example.
Synchronization in java with example.
Synchronized method in java with example.
Static synchronization in java with example.
Synchronized block in java with example.

 


Comments are closed.