본문 바로가기

라이브러리 활용 - 멀티 스레드

스레드 안전 종료

안전하게 스레드 종료하기

  • 스레드 강제 종료 stop() 메소드: deprecated(더 이상 사용하지 않음)
  • 스레드를 안전하게 종료하려면 사용하던 리소스(파일, 네트워크 연결)를 정리하고 run() 메소드를 빨리 종료해야 함

조건 이용

  • while 문으로 반복 실행 시 조건을 이용해 run() 메소드 종료를 유도


    출처, 이것이 자바다


package ch14.sec07.exam01;

public class PrintThread extends Thread{
    private boolean stop; //기본값 false

    public void setStop(boolean stop) {
        this.stop = stop;
    }

    @Override
    public void run() {
        while(!stop) {
            System.out.println("실행 중");
        }
        System.out.println("리소스 정리");
        System.out.println("실행 종료");
    }
}

package ch14.sec07.exam01;

/*
 스레드 종료 :
  - boolean 변수를 사용.(flag 기법)
 */

public class SafeStopExample {

    public static void main(String[] args) {

        PrintThread printThread = new PrintThread();
        printThread.start();

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

        //외부 메인스레드에서  printThread 스레드를 종료상태를 제어함.
        printThread.setStop(true);
    }
}

interrupt() 메소드 이용

  • 스레드가 일시 정지 상태에 있을 때 InterruptedException 예외 발생
  • 예외 처리를 통해 run() 메소드를 정상 종료


    출처, 이것이 자바다


  • Thread의 interrupted()와 isInterrupted() 메소드는 interrupt() 메소드 호출 여부를 리턴


    출처, 이것이 자바다


package ch14.sec07.exam02;

public class PrintThread extends Thread {
    @Override
    public void run() {
        try {
            while(true) {
                System.out.println("실행 중");
                Thread.sleep(1);
            }
        } catch (InterruptedException e) {

        }
        System.out.println("리소스 정리");
        System.out.println("실행 종료");
    }
}

package ch14.sec07.exam02;

public class InterruptExample {

    public static void main(String[] args) {
        Thread thread = new PrintThread();
        thread.start();

        //메인 스레드가 1초 일시정지 되면, thread 스레드가 실행이 될수가 있다.
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {

        }
        // thread 스레드가 sleep()메소드를 호출한 상태에서, 아래 구문이 실행이 되면, 예외 발생
        //while문을 빠져나와 catch()로 진행되고, 나머지 실행을 한 후 종료된다.
        thread.interrupt(); //유무에 따라 결과 확인해보기
    }
}

'라이브러리 활용 - 멀티 스레드' 카테고리의 다른 글

스레드풀  (0) 2023.02.06
데몬 스레드  (1) 2023.02.06
스레드 동기화  (0) 2023.02.03
스레드 상태  (1) 2023.02.03
스레드 이름  (0) 2023.02.03