SeouliteLab

[Java/자바] Thread.join() 메서드 본문

프로그래밍

[Java/자바] Thread.join() 메서드

Seoulite Lab 2024. 3. 15. 15:55

Java의 Thread.join() 메서드

Java에서는 멀티스레드 프로그래밍을 위해 Thread 클래스를 제공합니다. 이 클래스에는 여러 스레드를 조정하고 관리하기 위한 다양한 메서드가 있습니다. 그 중 하나가 join() 메서드인데, 이를 사용하여 특정 스레드가 종료될 때까지 대기할 수 있습니다. 이 글에서는 join() 메서드의 사용법과 예제를 살펴보겠습니다.

1. 기본적인 join() 메서드 사용법

가장 간단한 형태의 join() 메서드를 살펴보겠습니다. 이 메서드는 호출한 스레드가 대상 스레드의 작업이 끝날 때까지 기다리도록 합니다.

public class BasicJoinExample {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Thread is running: " + i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        
        // 새로운 스레드 시작
        thread.start();
        
        // 새로운 스레드 종료될 때까지 대기
        thread.join();
        
        System.out.println("Main thread exiting...");
    }
}

2. 여러 스레드의 join() 메서드 사용하기

여러 스레드가 생성되고 실행되는 상황에서 join() 메서드를 사용하는 방법을 살펴보겠습니다. 이 예제에서는 두 개의 스레드가 생성되어 실행되고, 각 스레드가 종료될 때까지 기다립니다.

public class MultipleJoinExample {
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Thread 1 is running: " + i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        Thread thread2 = new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                System.out.println("Thread 2 is running: " + i);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        // 스레드 1 시작
        thread1.start();
        // 스레드 2 시작
        thread2.start();

        // 각 스레드 종료될 때까지 대기
        thread1.join();
        thread2.join();

        System.out.println("Main thread exiting...");
    }
}