현재 쓰레드를 지정된 시간동안 멈추게 한다.
static 메서드이며 자기 자신에게만 동작한다.
Tip) yild() : 양보, 메서드도 마찬가지이다.
static void sleep(long millis) //천분의 일초 단위
static void sleep(long millis, int nanos) //천분의 알초 + 나노초
try{
Thread.sleep(1, 500000); //쓰레드를 0.0015초 동안 멈추게 한다.
} catch (InterruptedException e) {}
// 누가 깨우는 순간 예외를 발생시켜 잠자는걸 깨움
//////////////////
// 매번 예외처리 하기 불편하니 아예 매서드로 만듬
void delay(long millis)
{
try
{
Thread.sleep(millis);
} catch (InterruptedException e) { }
}
//delay()를 호출하여 쓰레드 실행
// 잘못된 방법
// 의도는 th1 쓰레드를 재우려 했지만, 본인이 잠들기 때문
try
{
th1.sleep(2000);
} catch(InterruptedException e) { }
/*-------------------------------*/
// 옳은 방법
try
{
Thread.sleep(2000);
} catch(Interrupted e) { }
ex)
class TreadTest{
public static void main(String[] args)
{
ThreadTest th1 = new ThreadTest1();
ThreadTest th2 = new ThreadTest2();
th1.start();
th2.start();
try{
th1.sleep(2000);
//th1을 2초동안 재울 것 같지만 본인을 재움
} catch(InterruptedException e) { }
System.out.println("<<main 종료>>>");
}//main
}
class ThreadTest1 extends Thread{
public void run(){
for(int i=0; i<300; i++) System.out.println("-");
System.out.println("<<th1 종료>>");
} //run()
}
class ThreadTest2 extends Thread{
public void run(){
for(int i=0; i<300; i++) System.out.println("\");
System.out.println("<<th2 종료>>");
} //run()
}
void interrupt()
//쓰레드의 interrupted상태를 false에서 true로 변경.
boolean isInterrupted()
//쓰레드 interrupted상태를 반환
static boolean interrupted()
//현재 쓰레드의 interrupted상태를 알려주고, false로 초기화
public static void main(String[] args){
ThreadTest1 th1 = new ThreadTest1();
th1.start();
th1.interrupt(); //interrupt()를 호출하면, interrupted true가 된다.
System.out.println("isInterrupted() :" + th1.isInterrupted()); //ture
}
// 자바 내부 코드
class Thread { //알기 쉽게 변경한 코드
boolean interrupted = false;
boolean isInterrupted(){
return interrupted;
}
boolean interrupted() {
interrupted = true;
}
}
- sleep()는 특정 메서드를 재울 수는 없다. 본인만 재운다.
- sleep()은 예외처리를 해줘야 한다.
따라서, 이를 편하게 하기 위해서 메서드안에 구현하고 호출하는 식으로 사용한다.(매번 예외처리가 번거로워서)- void interrupt()
쓰레드의 interrupted상태를 false에서 true로 변경.- boolean isInterrupted()
쓰레드 interrupted상태를 반환- static boolean interrupted()
현재 쓰레드의 interrupted상태를 알려주고, false로 초기화