-2

I am a beginner for Core Java and I'm now studying multithreading. I have one doubt that is related to this code:

import java.io.*;
public class MyThread extends Thread
{
   public void run()
   {
       for(int i=0;i<10;i++)
       {
           try
           {
               Thread.sleep(500);
           }
           catch(InterruptedException e)
           {
               System.out.println(e);
           }
           System.out.println(i);
       }
   }

   public static void main(String args[])
   {
       MyThread mt=new MyThread();
       MyThread mt1=new MyThread();
       mt.start();
       mt.start();
   }
}

The code above compiles, however I got an illegal state exception in run time. What is the reason for this?

edwoollard
  • 12,245
  • 6
  • 43
  • 74
user3503297
  • 59
  • 2
  • 7

1 Answers1

2

You are starting your first Thread mt twice, instead of starting mt1.

Once running, a Thread will throw IllegalStateException if you attempt to start it again.

Mena
  • 47,782
  • 11
  • 87
  • 106