Java Thread Sleep() Method Usage Guide
In Java, the sleep() method of Thread can pause the current thread for a period of time. The sleep() method takes a long integer parameter, representing the amount of time the thread should sleep, in milliseconds. For example, Thread.sleep(1000) indicates that the current thread should sleep for 1 second.
Here is a basic example code demonstrating how to use the sleep() method.
public class MyThread extends Thread {
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("Thread running: " + i);
try {
Thread.sleep(1000); // 休眠1秒
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
In the above example, we created a custom thread class MyThread that extends Thread, and we overrode the run() method. Within the run() method, we used the sleep() method to make the thread sleep for 1 second after each execution.
In the main method, we create an instance of MyThread and call the start() method to start the thread. The thread will output “Thread running: ” every 1 second.
It’s important to note that the sleep() method may throw an InterruptedException, so the exception needs to be caught in a try-catch block.