본문 바로가기
아카이브/자바의 정석

13장 쓰레드 20210104

by nineteen 2021. 1. 4.
반응형

새해가 됐다.

 

 

 

 

sleep(long millis) - 일정시간동안 쓰레드를 멈추게 함

 

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
31
32
class ThreadEx12_1 extends Thread {
    public void run() {
        for(int i=0; i<300; i++
            System.out.print("-");
        System.out.print("<<th1 종료>>");    
    }
}
 
class ThreadEx12_2 extends Thread {
    public void run() {
        for(int i=0; i<300; i++
            System.out.print("|");
        System.out.println("<<th2 종료>>");
    }
}
 
public class ThreadEx12 {
    public static void main(String[] args) {
        ThreadEx12_1 th1 = new ThreadEx12_1();    
        ThreadEx12_2 th2 = new ThreadEx12_2();
        th1.start();    // 쓰레드 시작
        th2.start();
        
        // sleep()을 사용하면 'InterruptedException'예외처리를 해줘야 함
        try {
            //th1.sleep(2000);    // sleep()은 현재 실행 중인 쓰레드에 대해 작동하기 때문에 main쓰레드에 영향
            Thread.sleep(2000);
        } catch(InterruptedException e) {}    
        
        System.out.println("<<main 종료>>");
    }
}
cs

24~28행을 유의

sleep()을 호출할 땐, 예외처리를 해줘야 함

항상 현재 실행중인 쓰레드에 대해 작동

 

 

 

interrupt()와 interrupted() - 쓰레드의 작업을 취소

 

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
import javax.swing.JOptionPane;
 
class ThreadEx13_1 extends Thread {
    public void run() {
        int i=10;
        
        // i가 0이 아니고 interrupted상태가 false가 아닐때까지 반복
        while(i!=0 && !isInterrupted()) {    
            System.out.println(i--);
            for(long x=0;x<2500000000L;x++);
        }
        System.out.println("카운트가 종료되었습니다.");
    }
}
 
public class ThreadEx13 {
    public static void main(String[] args) {
        ThreadEx13_1 th1 = new ThreadEx13_1();
        th1.start();    // 쓰레드 시작
        
        String input = JOptionPane.showInputDialog("아무 값이나 입력하세요");
        System.out.println("입력하신 값은 " + input + "입니다.");
        // 21,22행 실행 후, interrupted()실행
        th1.interrupt();// 쓰레드의 interrupted상태 -> true로 변경, 작업을 멈춤
        System.out.println("isInterrupted() : " + th1.isInterrupted());
    }
}
cs

입력을 하면 카운트가 종료됨

 

interrupt()를 호출하면 쓰레드의 interrupted상태가 true로 변경되고, 작업을 멈춘다.

 

 

 

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
31
32
33
package thread;
 
import javax.swing.JOptionPane;
 
class ThreadEx14_1 extends Thread {
    public void run() {
        int i=10;
        
        // i가 0이 아니고 interrupted상태가 false가 아닐때까지 반복
        while(i!=0 && !isInterrupted()) {    
            System.out.println(i--);
            try {
                Thread.sleep(1000);    // 쓰레드가 멈춰있을때, interrupt()를 실행하면 상태가 false로 변경
            } catch(InterruptedException e) {
                //interrupt();    // catch블럭에 interrupt()를 추가해 상태를 true로 바꾸면 30행에 의해 작업을 멈춤
            }
        }
        System.out.println("카운트가 종료되었습니다.");
    }
}
 
public class ThreadEx14 {
    public static void main(String[] args) {
        ThreadEx14_1 th1 = new ThreadEx14_1();
        th1.start();    // 쓰레드 시작
        
        String input = JOptionPane.showInputDialog("아무 값이나 입력하세요");
        System.out.println("입력하신 값은 " + input + "입니다.");
        // 27,28행 실행 후, interrupted()실행
        th1.interrupt();// 13행에 의해 쓰레드의 interrupted상태 -> false로 변경, 작업을 계속 진행
        System.out.println("isInterrupted() : " + th1.isInterrupted());
    }
}
cs

입력을 해도 카운트가 종료 안됨

 

sleep()에 의해 쓰레드가 잠시 멈춰있을 때, interrupt()를 호출하면 InterruptedException이 발생되고 쓰레드의 interrupted상태는 false로 초기화 됨

 

이를 해결하기 위해 15행, catch블럭에 interrupt()를 추가해 interrupted상태를 다시 true로 바꿔주면 Thread13예제와 같은 결과 출력 가능

'아카이브 > 자바의 정석' 카테고리의 다른 글

자바의 정석 15장 입출력  (0) 2021.12.23
13장 쓰레드 20200106  (0) 2021.01.06
13장 Thread 20201120  (0) 2020.11.20
13장 Thread 20201118  (0) 2020.11.18
12장 지네릭스,열거형,애노테이션 20201116  (0) 2020.11.16