Sunday, 20 October 2013

java.lang.IllegalThreadStateException



package com.javastoreroom.thread;

import java.sql.Timestamp;
import java.util.Date;

public class ThreadSleeping extends Thread {

 public void run() {
       Date date = new Timestamp(System.currentTimeMillis());
       
  for (int i = 0; i < 10; i++) {
   try {
    Thread.sleep(1000);
   } catch (Exception e) {
    e.printStackTrace();
   }
   System.out.print(i +",\t");
  }
 }

 public static void main(String[] args) {
  ThreadSleeping sleeping = new ThreadSleeping();
  sleeping.start();
 }

}
if you run above example following output shown :-
if you change the main block code to this :-
public static void main(String[] args) {
  ThreadSleeping sleeping = new ThreadSleeping();
  sleeping.start();
  sleeping.start();
 }

You will get java.lang.IllegalThreadStateException exception reason behind the exception is you are trying to start the thread twice. you are trying to start something which is already started, so you getting IllegalThreadStateException. Another reason behind the exception if you mark user thread as a daemon thread . it not be started and throw IllegalThreadStateException .
ThreadSleeping sleeping = new ThreadSleeping();
  sleeping.start();
  sleeping.setDaemon(true); // throw exception
 
Exception in thread "main" java.lang.IllegalThreadStateException
 at java.lang.Thread.start(Thread.java:656)
 at com.javastoreroom.thread.ThreadSleeping.main(ThreadSleeping.java:24)
:)

No comments:

Post a Comment