/*When
you try to invoke the start method on the same thread twice the second thread will not start and result
into exception.Also first thread will not stops its execution*/
package threading;
public class Self extends Thread{
@Override
public void run() {
for (int i=0;i<5;i++)
{
System.out.println(i+" Thread name is "+Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Thread t = new Thread(new Self());
t.start();
t.start(); //exception will throw and second thread will not start
}
}
/* Output:
*
* Exception in thread "main" 0 Thread name is Thread-1
java.lang.IllegalThreadStateException
at java.lang.Thread.start(Unknown Source)
at threading.Self.main(Self.java:28)
1 Thread name is Thread-1
2 Thread name is Thread-1
3 Thread name is Thread-1
4 Thread name is Thread-1
*/
No comments:
Post a Comment