Home  >  Article  >  Java  >  What is the purpose of Thread.sleep() method in Java?

What is the purpose of Thread.sleep() method in Java?

WBOY
WBOYforward
2023-09-05 16:05:161376browse

What is the purpose of Thread.sleep() method in Java?

sleep() method is a static method of the Thread class, which makes the thread >Sleep/Stop Works for a specific period of time. If a thread is interrupted by other threads, the sleep() method will throw InterruptedException, which means that the Thread.sleep() method must be included in try, and catch Block or must be specified with throwing clause . Whenever we call the Thread.sleep() method, it interacts with the thread scheduler to put the current thread in a waiting state for a period of time. specific time period. Once the waiting time has elapsed, the thread changes from the waiting state to the runnable state.

Syntax

public static void sleep(long milliseconds)
public static void sleep(long milliseconds, int nanoseconds)

sleep(long milliseconds) method causes the thread to sleep only for certain milliseconds.

sleep(long milliseconds) method causes the thread to sleep only for certain milliseconds. milliseconds, integer nanoseconds) Method causes the thread to sleep for some specific milliseconds and nanoseconds.

Example

class UserThread extends Thread {
   public void run() {
      for(int i=1; i <= 5; i++) {
         System.out.println("User Thread");
         try {
<strong>           </strong> Thread.sleep(1000); // sleep/stop a thread for 1 second<strong>
</strong>         } catch(InterruptedException<strong> </strong>e) {
            System.out.println("An Excetion occured: " + e);
         }
      }
   }
}
public class SleepMethodTest {
   public static void main(String args[]) {
      UserThread ut = new UserThread();
<strong>     </strong> ut.start(); // to start a thread
   }
}

Output

User Thread
User Thread
User Thread
User Thread
User Thread

The above is the detailed content of What is the purpose of Thread.sleep() method in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete