• Post Reply Bookmark Topic Watch Topic
  • New Topic

infinite loop in run  RSS feed

 
faiza haris
Ranch Hand
Posts: 173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If run() has an infinite loop when started,then the thread doesnt start at once but goes
in ReadytoRun stage, where it waits for other threads and the schedular decides when to run this thread? Am i right? Anything to be added to it?
2) Also if i put an infinite loop in main , it gives Unreachable Statement error. It did not
give this error when infin. loop is in run() method???why???

[This message has been edited by Jim Yingst (edited November 29, 2000).]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1) After start(), the thread moves to the ready state, and then in all likelihood it goes to the run state. Since your loop doesn't actually do anything you can't see that it runs - try putting a print statement in the loop, and you'll see that it actually is running. It doesn't matter whether there is an infinite loop or not - this is the normal way a thread starts.
2) Basically, it depends how smart your compiler is. There's a limit to how much work your compiler is willing to do to figure out if a statement is really reachable or not - if you hide the infinite loop in a separate method, the compiler won't try as hard to figure out what's going on. The compiler isn't required to reject all unreachable statements - only the ones it notices.
[This message has been edited by Jim Yingst (edited November 29, 2000).]
 
faiza haris
Ranch Hand
Posts: 173
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
/*Somehow i am confused that calling the start method will invoke the run() method. Because then it would print
Starting in main , go to the loop in run and print "running run " and then print "after start". What
actually happens is that i get Starting main, then "after start" 10 times and then "running run" 10 times.
My logic:
that maybe because the thread when started is in Ready state and the thread printing "after start" is in
running stage???
But then how can i know by having a look at the program about the current stage of the thread???
Plz help
*/
public class Testthreadinfinite extends Thread
{
public void run()
{
for (int i=0; i<10; i++){
System.out.println("running run");}
}
public static void main(String args[])
{
System.out.println("Starting main");

new Testthreadinfinite().start();
for (int i=0; i<10; i++){
System.out.println("after start");
}
}
}
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!