Computer >> 컴퓨터 >  >> 프로그래밍 >> Java

자바 Thread 클래스의 join() 메소드 완벽 이해하기

join() 메소드란?

자바에서 join() 메소드는 현재 실행 중인 스레드가 다른 스레드의 작업이 끝날 때까지 기다리도록 만드는 기능을 합니다. 즉, join()이 호출된 대상 스레드가 종료될 때까지 호출한 스레드는 대기 상태에 머무르게 됩니다.

예를 들어, 메인 스레드에서 특정 작업 스레드에 대해 join()을 호출하면, 해당 작업 스레드가 모든 작업을 마친 후에야 메인 스레드가 다음 코드를 실행할 수 있습니다. 여러 스레드 간의 실행 순서를 제어해야 할 때 매우 유용한 메소드입니다.

문법

final void join() throws InterruptedException

join() 메소드는 InterruptedException을 던질 수 있으므로 반드시 try-catch 블록으로 감싸거나 예외를 선언해야 합니다.

예제 코드

public class Demo extends Thread{
    public void run(){
        System.out.println("sample ");
        try{
            Thread.sleep(10);
        }
        catch (InterruptedException ie){
        }
        System.out.println("only ");
    }
    public static void main(String[] args){
        Demo my_obj_1 = new Demo();
        Demo my_obj_2 = new Demo();
        my_obj_1.start();
        System.out.println("The first object has been created and started");
        try{
            System.out.println("In the try block, the first object has been called with the join function");
            my_obj_1.join();
        }
        catch (InterruptedException ie){
        }
        System.out.println("The second object has been started");
        my_obj_2.start();
    }
}

실행 결과

The first object has been created and started
In the try block, the first object has been called with the join function
sample
only
The second object has been started
sample
only

코드 설명

위 예제에서는 Demo라는 클래스가 Thread 클래스를 상속받습니다. 이 클래스 내부에는 run() 메소드가 정의되어 있으며, 그 안에 try-catch 블록이 포함되어 있습니다. try 블록에서는 sleep() 함수를 호출하여 잠시 대기하고, catch 블록은 비워 두었습니다.

main() 메소드에서는 Demo 객체의 인스턴스 두 개를 생성합니다. 첫 번째 객체를 start()로 실행한 뒤 join() 메소드를 호출하여, 첫 번째 스레드의 작업이 완전히 끝날 때까지 메인 스레드가 대기하도록 합니다. 이후 두 번째 객체를 시작하며, 각 단계마다 적절한 메시지를 출력합니다.

실행 흐름 분석

출력 결과를 보면 첫 번째 객체가 start()된 후 join()이 호출되어 "sample"과 "only"가 먼저 출력되고, 그다음에야 두 번째 객체가 시작되어 동일한 출력이 반복되는 것을 확인할 수 있습니다. 만약 join()을 사용하지 않았다면 두 스레드가 동시에 실행되어 출력 순서가 매번 달라졌을 것입니다.

join()의 주요 특징 정리

  • join()이 호출된 스레드가 종료될 때까지 현재 스레드는 무기한 대기합니다.
  • 시간을 지정하는 join(long millis) 오버로드를 사용하면 최대 대기 시간을 설정할 수 있습니다.
  • 대기 중 인터럽트가 발생하면 InterruptedException이 발생합니다.