Notice
Recent Posts
Recent Comments
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

충분히 쌓여가는

sleep(), interrupt() 본문

Java/JAVA3

sleep(), interrupt()

빌드이너프 2023. 8. 4. 11:29

sleep()

현재 쓰레드를 지정된 시간동안 멈추게 한다

static 메서드이기 때문에 쓰레드 자기자신한테만 동작한다(static 메서드: sleep(), yield())

static void sleep(long millis) // 천 분의 일 초 단위
static void sleep(long millis, int nanos) // 천분의 일 초 + 나노 초

 

예외처리를 해야한다(InterruptedException이 발생하면 깨어남)

InterruptedException이 필수 예외이기 때문

try {
    Thread.sleep(1, 500000); // 쓰레드를 0.0015초 동안 멈추게 한다
} catch(InterruptedException e) {}

 

항상 예외처리 해주기 힘듬 => delay 메서드 생성, sleep 대신 호출

void delay(ling millis) {
    try {
        Thread.sleep(millis);
    } catch(InterruptedException e) {}
}

 

sleep()는 자기 자신에게만 적용되기 때문에, 특정 쓰레드를 지정해서 멈추게 하는 것은 불가능하다

th1을 sleep()라고 오해할 수 있기 때문에 Thread 즉, 클래스 이름 호출해야 한다

 

코드

class sleepTest {
    public static void main(String args[]) {
        sleepTest_1 th1 = new sleepTest_1();
        sleepTest_2 th2 = new sleepTest_2();
        th1.start(); th2.start();

        try {
            Thread.sleep(2000);
        } catch(InterruptedException e) {}

        System.out.print("<<main 종료>>");
    } // main

}

class sleepTest_1 extends Thread {
    public void run() {
        for(int i=0; i < 300; i++) System.out.print("-");
        System.out.print("<<th1 종료>>");
    } // run()
}

class sleepTest_2 extends Thread {
    public void run() {
        for(int i=0; i < 300; i++) System.out.print("|");
        System.out.print("<<th2 종료>>");
    } // run()
}

<<main 종료>>가 2초 뒤에 출력된다

 

delay 메서드 생성

예외처리 되어있는 메서드를 만들어두면 예외처리를 매번 할 필요가 없다

class sleepTest {
    public static void main(String args[]) {
        sleepTest_1 th1 = new sleepTest_1();
        sleepTest_2 th2 = new sleepTest_2();
        th1.start(); th2.start();

        delay(2 * 1000);
        System.out.print("<<main 종료>>");
    } // main

    static void delay(long millis) {
        try {
            Thread.sleep(2000);
        } catch(InterruptedException e) {}

    }
}

class sleepTest_1 extends Thread {
    public void run() {
        for(int i=0; i < 300; i++) System.out.print("-");
        System.out.print("<<th1 종료>>");
    } // run()
}

class sleepTest_2 extends Thread {
    public void run() {
        for(int i=0; i < 300; i++) System.out.print("|");
        System.out.print("<<th2 종료>>");
    } // run()
}

<<main 종료>>가 2초 뒤에 출력된다


 

interrupt()

대기상태(WAITING)인 쓰레드를 실행대기 상태(RUNNABLE)로 만든다

다운로드 도중 취소버튼 기능을 만드는 경우와 비슷함, 게임 종료 후 계속하시겠습니까와 비슷함

void interrupt() // 쓰레드의 interrupted 상태를 false에서 true로 변경
boolean isInterrupted() // 쓰레드의 interrupted 상태를 반환
static boolean interrupted() // 현재 쓰레드이 interrupted 상태를 알려주고, false로 초기화

 

public static void main(String[] args) {
    ThreadTest th1 = new ThreadTest();
    th1.start();
        ...
    th1.interrupt(); // interrupt()를 호출하면, interrupted 상태가 true가 된다
        ...
    System.out.println(th1.isInterrupted()); // true
}

 

코드

import javax.swing.JOptionPane;

class sleepTest {
    public static void main(String[] args) throws Exception {
        Thread_1 th1 = new Thread_1();
        th1.start();

        System.out.println("isInterrupted():"+ th1.isInterrupted()); // false
        String input = JOptionPane.showInputDialog("아무 값이나 입력하세요.");
        System.out.println("입력하신 값은 " + input + "입니다.");
        th1.interrupt();  // interrupt()를 호출하면, interrupted상태가 true가 된다.
        System.out.println("isInterrupted():"+ th1.isInterrupted()); // true

        // main 쓰레드가 interrupt 되었는지 확인
        System.out.println("interrupted():"+ Thread.interrupted()); // false, th1.interruped()로 하지 않게 주의, th1 사용해도 Thread(static 메서드이기 때문)
    }
}

class Thread_1 extends Thread {
    public void run() {
        int i = 10;

        while(i!=0 && !isInterrupted()) {
            System.out.println(i--);
            for(long x=0;x<2500000000L;x++); // 시간 지연
        }
        System.out.println("카운트가 종료되었습니다.");
    }
}


10
isInterrupted():false
9
2023-08-04 11:27:06.213 java[60583:194671] TSM AdjustCapsLockLEDForKeyTransitionHandling - _ISSetPhysicalKeyboardCapsLockLED Inhibit
8
7
6
5
4
3
2
입력하신 값은 asd입니다.
isInterrupted():true
interrupted():false
카운트가 종료되었습니다.