[JAVA] 일정시간 이후에 자바 쓰레드 강제종료 시키기 (java thread interrupt)

[JAVA] 일정시간 이후에 자바 쓰레드 강제종료 시키기 (java thread interrupt)

 

심각하게 오래 진행되는 프로세스가 있을 경우, 특정 Thread를 중지시켜야 하는 경우가 있다.

이 경우 killerThread 라는 걸 만들어서, 특정 Thread 의 소요시간이 오래 걸릴 경우 interrupt 해주면 된다.

참고로 killerThread와 특정 Thread는 서로가 서로를 겨누고 있어야 한다.

즉, 일정 시간이 지나면 killerThread가 특정 Thread를 interrupt 해야 하지만,

특정 Thread가 진행되는게 빠를 경우에는 특정 Thread 종료시 killerThread를 제거해야 한다.

package com.bb.test;

public class MainClass {

    public static void main(String[] args) {
        
        System.out.println(“메서드 호출하기 전”);
        
        MainClass mainClass = new MainClass();
        mainClass.doSomething();
        
        System.out.println(“메서드 호출 이후”);
    }

    
    public void doSomething() {
        
        System.out.println(“프로세스 시작”);
        
        // 현재 Thread 를 변수에 저장
        final Thread currentThread = Thread.currentThread();
        
        // 일정시간 지나면 현재 Thread 를 종료
        Thread killerThread = new Thread() {
            
            @Override
            public void run() {
                try {
                    // 1분 후 종료
                    Thread.sleep(60000);
                    
                } catch (InterruptedException e) {
                    // 킬러 Thread 종료(killerThread.interrupt())하면 이곳에 도달
                    System.out.println(“프로세스 종료”);
                    return;
                    
                } catch (Exception e) {
                    // 무시
                }
                
                try {
                    // 일정시간이 지나면 이곳에 도달
                    System.out.println(“시간초과로 인해 종료합니다.”);
                    
                    // 현재 Thread 를 종료
                    currentThread.interrupt();
                    
                } catch (Exception e) {
                    // 무시
                }
            }
        };
            
            
        try {
            // 일정시간 지나면 현재 Thread 를 종료
            killerThread.start();
            
            int limit = 999999;
            for (int i=0; i<limit; i++) {
                System.out.println(“진행중… (“ + (i+1) + ” / “ + limit + “)”);
                Thread.sleep(1000);
            }
            
        } catch (InterruptedException e) {
            System.out.println(“프로세스가 너무 오래 실행되고 있습니다. 프로세스를 종료합니다.”);
            
        } catch (Exception e) {
            e.printStackTrace();
            
        } finally {
            // 킬러 Thread 종료
            try {
                killerThread.interrupt();
            } catch (Exception e) {
                // 무시
            }
        }
    }