Originally posted by Usha Vydyanathan:
Hi,
I thought if a statement is unreachable Java always gives error.
Following code compiles fine eventhough "System.out.println("After stop method");" is not reachable because thread will stop before that.
public class Q1 extends Thread
{
public void run()
{
System.out.println("Before start method");
this.stop();
System.out.println("After stop method");
}
public static void main(String[] args)
{
Q1 a = new Q1();
a.start();
}
}
Can any one explain? Thanks in advance.
regards,
Usha
It is a good question .Yah if u are not using threads u get definitely a compile-time Objection to the code for java doesn't allow redundant code but in case of a thread when u say stop the thread is nomore in running state and hence the code after that doesnt matter.
A little change in yr program can help u in understanding better
public class Q111 extends Thread
{
public void run()
{
System.out.println("Before start method");
this.stop();
System.out.println("After stop method");
}
public static void main(String[] args)
{
Q111 a = new Q111();
a.start();
Thread.currentThread().stop();//(1)
System.out.println("After stop in main");(2)
}
Now after line marked (1) the code doesnt execute and doesnt
give compile-time error also.Now if u remove (1)(2) will get executed and After stop in main printed.Here it is not unreachable code rather u can say that the code after the stop is not consudered at all while in case of an unreachable statement like
while(false){
System.out.println("After stop in main");
}
thread that is executing this statement is running while it is programming error because of which a redundant code is found in the running thread and as i said java takes it as a compile-time
error.
Hope that i am right.
sandeep