We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

thread sleep program

gudii9
gudii9 asked
on
Medium Priority
410 Views
Last Modified: 2012-05-11
>>public class TSleep extends Thread{
public static void main(String argv[]){
       TSleep t = new TSleep();
       t.start();
       }

       public void run(){
          try{
             while(true){
                  this.sleep(10);
                  System.out.println("looping while");
                 }
            }catch(InterruptedException ie){}
       }
}
 
   

I was running above program to see thread sleep after 10 milli second. But it never slept. It is going continuously in infinity loop. please advise.



Any ideas, resources, links, sample code highly appreciated. thanks in advance.
Comment
Watch Question

Awarded 2011
Awarded 2011

Commented:

But when you say while(true) {...}
and inside your loop there is no break;
so it will never get out of that loop,
because true is alwyas true

You should have something like that:


  int count =0;
      while(true){
                  this.sleep(10);
                  System.out.println("looping while");
                 count++;
         if (count > 10) break;
                 }

Awarded 2011
Awarded 2011
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
>>>

What will happen when you attempt to compile and run this code?

public class TGo implements Runnable{
public static void main(String argv[]){
        TGo tg = new TGo();
        Thread t = new Thread(tg);
        t.start();
        }
        public void run(){
                while(true){
                        Thread.currentThread().sleep(1000);
                        System.out.println("looping while");
                        }
        }
}
1) Compilation and no output
2) Compilation and repeated output of "looping while"
3) Compilation and single output of "looping while"
4) Compile time error



similar lines this program wont give the exception also. please advise
Awarded 2011
Awarded 2011

Commented:
This will give compile error because line

Thread.currentThread().sleep(1000);


requires InterruptedException to be caught
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.