Advertisement
class ThRun implements Runnable //implementing the Runnable interface
{
public void run() //Entry point of new thread
{
for(int i=0;i<5;i++)
{
System.out.println(i);
}
}
public static void main(String... ar)
{
ThRun newTh= new ThRun();
Thread th= new Thread(newTh, "Thread2"); //Calling Thread's constructor & passing the object
//of class that implemented Runnable interface
//& the name of new thread.
//Stating the thread(Thread2).
th.start();
//Starting thread(Thread2) again, when it's already running, causing IllegalStateException.
th.start();
//This won't be printed because the main thread is halted by IllegalStateException
System.out.println("Main Thread");
}
}
0Exception in thread "main"
1
2
3
4java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at ThRun.main(Thread8.java:21)
Advertisement
class ThRun implements Runnable
{
public void run() //Entry point of new thread
{
for(int i=0;i<5;i++)
{
System.out.println(i);
}
}
public static void main(String... ar)
{
ThRun newTh= new ThRun();
Thread th= new Thread(newTh,"Thread2"); //Calling Thread's constructor & passing the object
//of class that implemented Runnable interface
//& the name of new thread.
//Stating the thread(Thread2).
th.start();
try
{
System.out.println("Main Thread is going to sleep");
Thread.sleep(3000); //Making main thread sleep for 3000ms / 3 seconds
System.out.println("Main thread is awakened");
}
catch(Exception e)
{
System.out.println(e);
}
//Calling start() method on a dead thread, causing IllegalStateException
th.start();
//This won't be printed because the main thread is halted by IllegalStateException
System.out.println("Main Thread");
}
}
Main Thread is going to sleep
0
1
2
3
4
Main thread is awakened
Exception in thread "main" java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at ThRun.main(Thread8.java:32)
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement