Page 1 of 2 12 LastLast
Results 1 to 20 of 26
  1. #1
    esha is offline Member
    Join Date
    Jan 2014
    Posts
    8
    Rep Power
    0

    Default Java Thread - Sleep

    Hi All,

    I've come a crossed following java code in one of the Java Books, I'm having difficulty of understanding some of the concepts here, Appreciate your help on this.

    Java Code:
    class ThreadTest {
      public static void main(String []args) throws InterruptedException {
          Thread t1 = new Thread() { public void run() { System.out.print("t1 "); } };
          Thread t2 = new Thread() { public void run() { System.out.print("t2 "); } };
          t1.start();
          t1.sleep(5000);
          t2.start();
          t2.sleep(5000);
          System.out.println("main ");
      }
    }

    I have following questions,

    1. Why t2.start() execution holds till the execution of t1.sleep(5000), I thought t1 and t2 are parallel executions and no dependancy on each other.
    2. Why it's not required to wrap t1.sleep(5000) with try catch block on main method ? I noticed Thread.sleep() needs to be wrapped with try catch if its in run method.

    Thanks in Advance.

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,598
    Rep Power
    5

    Default Re: Java Thread - Sleep

    Well, to answer your first question, sleep does not cause the invoking method instance to sleep. You are simply using the instance to wait 5 seconds in the main method before starting the next thread. So t1.sleep(5000) and t2.sleep(5000) are doing the same thing. In fact, it is bad technique to invoke sleep with an instance of the Thread class since sleep is declared static.

    If you want each thread to sleep before printing out their values, put a sleep() call just before the print statement inside of the run() method.
    To answer your second question, you would normally have to use a try catch block, but your main method is declared to throw the InterruptedException so you don't need one. Now if some other thread were to invoke main via ThreadTest.main(null), then that call would need to be in a try catch block.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  3. #3
    gimbal2 is online now Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,981
    Rep Power
    5

    Default Re: Java Thread - Sleep

    Just as an addition, check out the javadoc of Thread.sleep().

    Google: java 7 Thread
    Thread (Java Platform SE 7 ) (class)
    Thread (Java Platform SE 7 ) (sleep method)

    Note how the sleep() method is in fact static.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  4. #4
    esha is offline Member
    Join Date
    Jan 2014
    Posts
    8
    Rep Power
    0

    Default Re: Java Thread - Sleep

    Thanks Jim !
    Quick clarification, So this sleep in main method is not associated to t1 or t2 but it's associated to main method ?

  5. #5
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,598
    Rep Power
    5

    Default Re: Java Thread - Sleep

    Correct! In fact, if you replace t1 and t2 on your sleep calls with Thread, it should behave the same way.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  6. #6
    gimbal2 is online now Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,981
    Rep Power
    5

    Default Re: Java Thread - Sleep

    Quote Originally Posted by jim829 View Post
    Correct! In fact, if you replace t1 and t2 on your sleep calls with Thread, it should behave the same way.

    Regards,
    Jim
    and that is in fact the only correct way to call a static method; never through an instance variable, always through the class. I believe that most IDEs will actually provide a warning by default when you do it the wrong way.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  7. #7
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,598
    Rep Power
    5

    Default Re: Java Thread - Sleep

    Yep! And just to confirm, I did say that in my first reply. But reinforcement is always a good thing.

    Regards,
    Jim
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  8. #8
    gimbal2 is online now Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,981
    Rep Power
    5

    Default Re: Java Thread - Sleep

    Oops, I -totally- missed that. Nothing to see here, moving along.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  9. #9
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: Java Thread - Sleep

    Out of curiosity, what book is this from?
    Get in the habit of using standard Java naming conventions!

  10. #10
    esha is offline Member
    Join Date
    Jan 2014
    Posts
    8
    Rep Power
    0

    Default Re: Java Thread - Sleep

    Oracle Certified Professional - Java SE 7 (OCPJP Study Gude) by S G Ganesh & T Sharma.

    This is put as an question in this book as follows. Really helped me to deep dive and investigate more on this and learned lot from you guys. Thanks for the Help


    From the Book.


    2. Consider the following program and choose the correct option describing its behavior.

    class ThreadTest {
    public static void main(String []args) throws InterruptedException {
    Thread t1 = new Thread() { public void run() { System.out.print("t1 "); } };
    Thread t2 = new Thread() { public void run() { System.out.print("t2 "); } };
    t1.start();
    t1.sleep(5000);
    t2.start();
    t2.sleep(5000);
    System.out.println("main ");
    }
    }

    A. t1 t2 main
    B. t1 main t2
    C. main t2 t1
    D. This program results in a compiler error.
    E. This program throws a runtime error.
    Answer: A. t1 t2 main

  11. #11
    gimbal2 is online now Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,981
    Rep Power
    5

    Default Re: Java Thread - Sleep

    Note to self: don't copy code that is part of a trivia question, because trivia questions are usually designed to trick you, not to provide you correct code.

    If you don't understand the code, then go back to the chapters that discuss the subject matter and take a look at the code that is presented there.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  12. #12
    esha is offline Member
    Join Date
    Jan 2014
    Posts
    8
    Rep Power
    0

    Default Re: Java Thread - Sleep

    Thanks

  13. #13
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: Java Thread - Sleep

    The output will probably be A, but there are no guarantees about thread scheduling. It could also be B or C, or another order not shown. Between their misuse of Thread.sleep() and giving the wrong answer to their own question, I would be very skeptical about the qualifications of the authors...
    Get in the habit of using standard Java naming conventions!

  14. #14
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    3,598
    Rep Power
    5

    Default Re: Java Thread - Sleep

    I guess it could be something other than A. For example, if the the thread scheduler waits longer than 5 seconds to start the first thread while starting the next thread immediately. But that would be a terrible JRE implementation, IMO.

    Regards,
    Jim
    Last edited by jim829; 02-07-2014 at 12:44 AM.
    The Java™ Tutorial | SSCCE | Java Naming Conventions
    Poor planning our your part does not constitute an emergency on my part.

  15. #15
    manik90 is offline Member
    Join Date
    Feb 2014
    Posts
    1
    Rep Power
    0

    Default Re: Java Thread - Sleep

    Hi
    Simple thread introduction is available in Introduction to Threads - CodenRead

    also you can learn more about java form CodenRead - Tech Blog,Android apps,Programming tutorial, SEO

  16. #16
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,514
    Blog Entries
    7
    Rep Power
    20

    Default Re: Java Thread - Sleep

    It would be silly to be able to make any other but the current thread go to sleep; any arbitrary thread can reach any other thread through the ThreadGroup objects; also e.g. the garbage collector thread is reachable; imagine the havoc if it is made to fall asleep for a long time ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  17. #17
    gimbal2 is online now Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,981
    Rep Power
    5

    Default Re: Java Thread - Sleep

    Quote Originally Posted by JosAH View Post
    It would be silly to be able to make any other but the current thread go to sleep; any arbitrary thread can reach any other thread through the ThreadGroup objects; also e.g. the garbage collector thread is reachable; imagine the havoc if it is made to fall asleep for a long time ...

    kind regards,

    Jos
    I had to read that a couple of times before I got the intention there.

    edit: and my suggested correction made it even worse. *snip*. Now where is that button on my head to turn on my brain!?
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  18. #18
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,514
    Blog Entries
    7
    Rep Power
    20

    Default Re: Java Thread - Sleep

    iow: a thread (any thread) can find any other thread (through the ThreadGroup hierarchy); the garbage collection thread can also be found; imagine what would happen if you can put that thread to sleep ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  19. #19
    gimbal2 is online now Just a guy
    Join Date
    Jun 2013
    Location
    Netherlands
    Posts
    3,981
    Rep Power
    5

    Default Re: Java Thread - Sleep

    I wonder what the purpose is to be able to reach the garbage collection thread so easily (and BAM: learned something new). For monitoring purposes I guess.
    "Syntactic sugar causes cancer of the semicolon." -- Alan Perlis

  20. #20
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default Re: Java Thread - Sleep

    If you wanted to be totally evil, couldn't you disrupt the GC thread like this?

    Java Code:
    Object evil = new Object() {
       protected void finalize() throws Throwable {
          Thread.sleep(Long.MAX_VALUE);
       }
    }
    evil = null;
    Get in the habit of using standard Java naming conventions!

Page 1 of 2 12 LastLast

Similar Threads

  1. Thread.Sleep
    By allaudin in forum New To Java
    Replies: 2
    Last Post: 07-17-2013, 07:22 AM
  2. Replies: 1
    Last Post: 09-24-2012, 07:01 PM
  3. Difference between Thread.yield() and Thread.sleep() methods
    By Nageswara Rao Mothukuri in forum New To Java
    Replies: 12
    Last Post: 07-30-2010, 05:37 PM
  4. how to reduce the thread sleep time and wake up the thread
    By baktha.thalapathy in forum Threads and Synchronization
    Replies: 2
    Last Post: 06-24-2010, 07:36 PM
  5. Sleep in thread
    By jithan in forum New To Java
    Replies: 1
    Last Post: 08-27-2008, 02:27 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •