Java — Java.lang.Thread.sleep() Method | Code Factory

/* Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors. */
public static void sleep(long millis) throws InterruptedException
/* Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds plus the specified number of nanoseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors. */
public static void sleep(long millis, int nanos) throws InterruptedException
package com.example.thread;/**
* @author code.factory
*
*/
public class ThreadSleep {
public static void main(String... args) throws InterruptedException {
for(int i=0; i<5; i++) {
System.out.println(i);
Thread.sleep(1000);
}
}
}
0
1
2
3
4
/* Interrupts this thread. */
public void interrupt()
package com.example.thread;/**
* @author code.factory
*
*/
public class ThreadSleep {
public static void main(String... args) throws InterruptedException {
MyThread t = new MyThread();
t.start();
t.interrupt(); // #1
System.out.println("Main Thread end");
}
}
class MyThread extends Thread {
public void run() {
try {
for(int i=0; i<5; i++) {
System.out.println("Child Thread");
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Main Thread end
Child Thread
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.example.thread.MyThread.run(ThreadSleep.java:21)
package com.example.thread;/**
* @author code.factory
*
*/
public class ThreadSleep {
public static void main(String... args) throws InterruptedException {
MyThread t = new MyThread();
t.start();
t.interrupt();
System.out.println("Main Thread end");
}
}
class MyThread extends Thread {
public void run() {
for(int i=0; i<5; i++) {
System.out.println("Child Thread");
}
System.out.println("Entering into sleeping state");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Main Thread end
Child Thread
Child Thread
Child Thread
Child Thread
Child Thread
Entering into sleeping state
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.example.thread.MyThread.run(ThreadSleep.java:23)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store