Java Multithreading sleep work notes

Source: Internet
Author: User

The Thread sleep methods are Thread. sleep (long millis) and Thread. sleep (long millis, int nanos)
Sleep () is measured in milliseconds.

Question 1: Which thread will sleep during sleep
Answer: which thread calls sleep and which will sleep

Problem 2. The main thread can sleep
Yes
Thread. sleep () is often called to wait for the program. For example, if you want your program to be periodically executed, you can write a code

The code is as follows: Copy code
Int a = 2
While (a> 1 ){
Run...
Thread. sleep (24*3600*1000); // run once a day
}

Let's look at an example.

The code is as follows: Copy code

Package com. javaer. thread;
 
Public class TSleep implements Runnable {
 
Public static void main (String [] args ){
Thread s1 = new Thread (new TSleep (), "S1 ");
Thread s2 = new Thread (new TSleep (), "S2 ");
S1.start ();
S2.start ();
 }
 
@ Override
Public void run (){
// TODO Auto-generated method stub
For (int I = 0; I <10; I ++ ){
System. out. println ("Thread" + Thread. currentThread (). getName () + "" + I + "times! ");
Try {
Thread. sleep (30 );
} Catch (InterruptedException e ){
E. printStackTrace ();
              }
      }
 }
 
}

Thread S1 0th executions!
Thread S2 0th executions!
Thread S1 1st Executions!
Thread S2 1st Executions!
Thread S1 2nd executions!
Thread S2 2nd executions!
Thread S2 3rd executions!
Thread S1 3rd executions!
Thread S1 4th executions!
Thread S2 4th executions!
Thread S1 5th executions!
Thread S2 5th executions!
Thread S2 6th executions!
Thread S1 6th executions!
Thread S1 7th executions!
Thread S2 7th executions!
Thread S2 8th executions!
Thread S1 8th executions!
Thread S1 9th executions!
Thread S2 9th executions!

The example shows that the time sleep of a thread is not precisely controlled, but close to precision. Sometimes thread s2 is executed first.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.