I tried overriding start() , even though its not required since extending thread means one can override run() that will be sufficient to do desired work . But again showing my stupidity i did that as below
public class MyThread extends Thread{
public void start()
{
System.out.println( " MyThread started " );
run();
}
public void run(){
for(int i =0 ; i < 3 ; i + + )
System.out.println( i );
throw new RuntimeException();
}
public static void main(String...a)
{
MyThread mt = new MyThread();
mt.start();
System.out.println ( " Done " );
}
}
And it made me puzzled that while running this program it executed in single threaded environment .
did you get the cause ?
because in order to spawn a new thread start() method must call super.start() from with in start() that internally invokes run() method of custom thread .Other wise it would have been a regular method call .
So i need to over start as below & no need to call run() explicitly
public void start(String... args)
{
System.out.println ( " MyThread started " );
super.start();
}
Next Time respect Thread little more ! :-)
public class MyThread extends Thread{
public void start()
{
System.out.println( " MyThread started " );
run();
}
public void run(){
for(int i =0 ; i < 3 ; i + + )
System.out.println( i );
throw new RuntimeException();
}
public static void main(String...a)
{
MyThread mt = new MyThread();
mt.start();
System.out.println ( " Done " );
}
}
And it made me puzzled that while running this program it executed in single threaded environment .
did you get the cause ?
because in order to spawn a new thread start() method must call super.start() from with in start() that internally invokes run() method of custom thread .Other wise it would have been a regular method call .
So i need to over start as below & no need to call run() explicitly
public void start(String... args)
{
System.out.println ( " MyThread started " );
super.start();
}
Next Time respect Thread little more ! :-)
No comments:
Post a Comment