SeouliteLab

[Java/자바] Thread.join()에 Timeout 적용 본문

프로그래밍

[Java/자바] Thread.join()에 Timeout 적용

Seoulite Lab 2024. 3. 15. 15:57

Java의 Thread.join() 메서드는 대기중인 스레드가 종료될 때까지 기다리는 기능을 제공합니다. 그러나 때로는 일정 시간 이상 대기하고자 할 때도 있습니다. 이를 위해 Timeout을 적용하는 방법을 살펴보겠습니다.

1. join() 메서드에 Timeout 적용하기

Java에서는 join(long milliseconds) 메서드를 사용하여 Timeout을 적용할 수 있습니다. 이 메서드는 지정된 시간(밀리초) 동안 대상 스레드가 종료될 때까지 대기하다가 Timeout이 발생하면 다음 작업으로 넘어갑니다.

public class JoinWithTimeoutExample {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            try {
                Thread.sleep(3000); // 3초 동안 대기
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        thread.start();

        // 지정된 시간(밀리초) 동안 대기, Timeout: 2초
        thread.join(2000);

        if (thread.isAlive()) {
            // Timeout 발생 시 처리할 작업
            System.out.println("Thread did not complete within the timeout period.");
        } else {
            System.out.println("Thread completed successfully.");
        }
    }
}

2. 여러 스레드에 각각 Timeout 적용하기

여러 스레드에 각각 다른 Timeout을 적용할 수도 있습니다. 아래 예제에서는 두 개의 스레드에 각각 다른 Timeout을 적용하여 Timeout이 발생하는 경우를 살펴봅니다.

public class MultipleJoinWithTimeoutExample {
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            try {
                Thread.sleep(3000); // 3초 동안 대기
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        Thread thread2 = new Thread(() -> {
            try {
                Thread.sleep(2000); // 2초 동안 대기
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        thread1.start();
        thread2.start();

        // 스레드 1의 Timeout: 2초
        thread1.join(2000);

        // 스레드 2의 Timeout: 3초
        thread2.join(3000);

        if (thread1.isAlive()) {
            System.out.println("Thread 1 did not complete within the timeout period.");
        } else {
            System.out.println("Thread 1 completed successfully.");
        }

        if (thread2.isAlive()) {
            System.out.println("Thread 2 did not complete within the timeout period.");
        } else {
            System.out.println("Thread 2 completed successfully.");
        }
    }
}