Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-09-05 16:05:16
forward
1406 people have browsed it

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)
Copy after login

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
   }
}
Copy after login

Output

User Thread
User Thread
User Thread
User Thread
User Thread
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template