logo

예제가 포함된 Java의 Thread.sleep()

Java Thread 클래스는 sleep() 메소드의 두 가지 변형을 제공합니다. 첫 번째 변형은 인수만 허용하는 반면, 다른 변형은 두 개의 인수를 허용합니다. sleep() 메소드는 주어진 시간 동안 스레드 작업을 중지하는 데 사용됩니다. 스레드가 휴면 상태로 유지되는 시간을 스레드의 휴면 시간이라고 합니다. 휴면 시간이 끝나면 스레드는 떠난 곳부터 실행을 시작합니다.

sleep() 메소드 구문:

다음은 sleep() 메소드의 구문입니다.

 public static void sleep(long mls) throws InterruptedException public static void sleep(long mls, int n) throws InterruptedException 

하나의 매개변수를 갖는 sleep() 메소드는 기본 메소드이며, 기본 메소드의 구현은 다른 프로그래밍 언어로 수행됩니다. 두 개의 매개변수를 갖는 다른 메소드는 기본 메소드가 아닙니다. 즉, 구현은 Java로 수행됩니다. sleep() 메서드의 시그니처에 static 키워드가 포함되어 있으므로 Thread 클래스의 도움으로 sleep() 메서드에 액세스할 수 있습니다. 네이티브 및 비네이티브 메서드 모두 확인된 예외를 발생시킵니다. 따라서 try-catch 블록이나 throws 키워드가 여기에서 작동할 수 있습니다.

Thread.sleep() 메서드는 모든 스레드에서 사용할 수 있습니다. 이는 다른 스레드나 기본 스레드가 sleep() 메서드를 호출할 수 있음을 의미합니다.

매개변수:

다음은 sleep() 메소드에 사용되는 매개변수입니다.

mls: 밀리초 단위의 시간은 매개변수 mls로 표시됩니다. 스레드가 휴면 상태에 있는 기간은 sleep() 메소드에 의해 지정됩니다.

N: 프로그래머나 개발자가 스레드가 절전 상태에 있기를 원하는 추가 시간을 보여줍니다. n의 범위는 0~999999입니다.

이 메서드는 아무것도 반환하지 않습니다.

Sleep() 메서드에 대해 기억해야 할 중요한 사항

Thread.sleep() 메서드가 실행될 때마다 항상 현재 스레드의 실행이 중단됩니다.

현재 스레드가 이미 절전 모드에 있는 동안 다른 스레드가 중단될 때마다 InterruptedException이 발생합니다.

스레드를 실행하는 시스템이 바쁜 경우 스레드의 실제 휴면 시간은 일반적으로 인수에 전달된 시간에 비해 더 깁니다. 그러나 sleep() 메소드를 실행하는 시스템의 로드가 적다면 스레드의 실제 휴면 시간은 인수에 전달된 시간과 거의 같습니다.

멍청한 평균

Java의 sleep() 메소드 예: 사용자 정의 스레드에서

다음 예제에서는 사용자 정의 스레드에서 sleep() 메서드를 사용하는 방법을 보여줍니다.

파일 이름: TestSleepMethod1.java

 class TestSleepMethod1 extends Thread{ public void run(){ for(int i=1;i<5;i++){ 500 the thread will sleep for milli seconds try{thread.sleep(500);}catch(interruptedexception e){system.out.println(e);} system.out.println(i); } public static void main(string args[]){ testsleepmethod1 t1="new" testsleepmethod1(); t2="new" t1.start(); t2.start(); < pre> <p> <strong>Output:</strong> </p> <pre> 1 1 2 2 3 3 4 4 </pre> <p>As you know well that at a time only one thread is executed. If you sleep a thread for the specified time, the thread scheduler picks up another thread and so on.</p> <h3>Example of the sleep() Method in Java : on the main thread</h3> <p> <strong>FileName:</strong> TestSleepMethod2.java</p> <pre> // important import statements import java.lang.Thread; import java.io.*; public class TestSleepMethod2 { // main method public static void main(String argvs[]) { try { for (int j = 0; j <5; 1 1000 j++) { the main thread sleeps for milliseconds, which is sec whenever loop runs thread.sleep(1000); displaying value of variable system.out.println(j); } catch (exception expn) catching exception system.out.println(expn); < pre> <p> <strong>Output:</strong> </p> <pre> 0 1 2 3 4 </pre> <h3>Example of the sleep() Method in Java: When the sleeping time is -ive</h3> <p>The following example throws the exception IllegalArguementException when the time for sleeping is negative.</p> <p> <strong>FileName:</strong> TestSleepMethod3.java</p> <pre> // important import statements import java.lang.Thread; import java.io.*; public class TestSleepMethod3 { // main method public static void main(String argvs[]) { // we can also use throws keyword followed by // exception name for throwing the exception try { for (int j = 0; j <5; j++) { it throws the exception illegalargumentexception as time is -ive which -100 thread.sleep(-100); displaying variable's value system.out.println(j); } catch (exception expn) iscaught here system.out.println(expn); < pre> <p> <strong>Output:</strong> </p> <pre> java.lang.IllegalArgumentException: timeout value is negative </pre> <hr></5;></pre></5;></pre></5;i++){>

여러분도 잘 알고 있듯이 한 번에 하나의 스레드만 실행됩니다. 지정된 시간 동안 스레드를 휴면 상태로 유지하면 스레드 스케줄러가 다른 스레드를 선택하는 식입니다.

Java의 sleep() 메소드 예: 메인 스레드

파일 이름: TestSleepMethod2.java

 // important import statements import java.lang.Thread; import java.io.*; public class TestSleepMethod2 { // main method public static void main(String argvs[]) { try { for (int j = 0; j <5; 1 1000 j++) { the main thread sleeps for milliseconds, which is sec whenever loop runs thread.sleep(1000); displaying value of variable system.out.println(j); } catch (exception expn) catching exception system.out.println(expn); < pre> <p> <strong>Output:</strong> </p> <pre> 0 1 2 3 4 </pre> <h3>Example of the sleep() Method in Java: When the sleeping time is -ive</h3> <p>The following example throws the exception IllegalArguementException when the time for sleeping is negative.</p> <p> <strong>FileName:</strong> TestSleepMethod3.java</p> <pre> // important import statements import java.lang.Thread; import java.io.*; public class TestSleepMethod3 { // main method public static void main(String argvs[]) { // we can also use throws keyword followed by // exception name for throwing the exception try { for (int j = 0; j <5; j++) { it throws the exception illegalargumentexception as time is -ive which -100 thread.sleep(-100); displaying variable\'s value system.out.println(j); } catch (exception expn) iscaught here system.out.println(expn); < pre> <p> <strong>Output:</strong> </p> <pre> java.lang.IllegalArgumentException: timeout value is negative </pre> <hr></5;></pre></5;>

Java의 sleep() 메소드 예: 수면 시간이 -ive인 경우

다음 예에서는 수면 시간이 음수일 때 예외 IllegalArguementException을 발생시킵니다.

파일 이름: TestSleepMethod3.java

 // important import statements import java.lang.Thread; import java.io.*; public class TestSleepMethod3 { // main method public static void main(String argvs[]) { // we can also use throws keyword followed by // exception name for throwing the exception try { for (int j = 0; j <5; j++) { it throws the exception illegalargumentexception as time is -ive which -100 thread.sleep(-100); displaying variable\'s value system.out.println(j); } catch (exception expn) iscaught here system.out.println(expn); < pre> <p> <strong>Output:</strong> </p> <pre> java.lang.IllegalArgumentException: timeout value is negative </pre> <hr></5;>