Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 213
  • Last Modified:

java programming in Thread

public class mythread extends Thread
{
      private boolean continuerun;
      public void setcontinuerun(boolean setc)
   {
         continuerun=setc;
   }
      public void run()
      {
            continuerun=true;
            while(continuerun)
            {
                  System.out.println("Iam running");
         }
                  System.out.println("Iam tired of running");
}
      public static void main(String args[])
      {
            mythread mm=new mythread();
            mm.start();
            //try
            //{
            //      Thread.currentThread().sleep(1000);
            //}
            //catch(InterruptedException ie)
            //{
      //}
            mm.setcontinuerun(false);
}
      }
My question is when is only when i add the sleep() method i could see the statement "Iam tired of running" ,why?
0
sraveend
Asked:
sraveend
  • 2
2 Solutions
 
TrekkyLeaperCommented:
The call to setcontinuerun(false) was coming too soon. I am guessing, you were seeing an infinite loop of "Iam running". When you call start(), it does not switch context to that thread immediately. When you called sleep(), the context had a chance to change to the "mm" thread.

To restate, without the sleep, you were setting continuerun to false before you had even set it to true and gotten into the loop. With the sleep, you get into the loop before you change the boolean variable.
0
 
CEHJCommented:
Possibly starvation of the explicitly created thread. Try

mm.setPriority(10);
0
 
sraveendAuthor Commented:
Could u suggest me any usefull link related to thread and synchronization
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now