join() 메서드란?
자바에서 join() 메서드는 한 스레드의 실행 시작을 다른 스레드의 실행 종료와 연결(join)하는 역할을 합니다. 즉, 어떤 스레드가 join()을 호출하면 대상 스레드의 작업이 끝나거나 지정된 시간이 경과할 때까지 현재 스레드는 대기 상태에 머무르게 됩니다. 이를 통해 스레드 간 실행 순서를 명확하게 보장할 수 있습니다.
join()은 밀리초(millisecond) 단위로 대기 시간을 지정할 수 있습니다. 지정한 시간이 지나면 더 이상 대기하지 않고 다음 코드를 실행하며, 인자 없이 호출하면 해당 스레드가 완전히 종료될 때까지 계속 기다립니다.
예제 코드
import java.lang.*;
public class Demo implements Runnable{
public void run(){
Thread my_t = Thread.currentThread();
System.out.println("The name of the current thread is " + my_t.getName());
System.out.println("Is the current thread alive? " + my_t.isAlive());
}
public static void main(String args[]) throws Exception{
Thread my_t = new Thread(new Demo());
System.out.println("The instance has been created and started");
my_t.start();
my_t.join(30);
System.out.println("The threads will be joined after 30 milli seconds");
System.out.println("The name of the current thread is " + my_t.getName());
System.out.println("Is the current thread alive? " + my_t.isAlive());
}
}실행 결과
The instance has been created and started The threads will be joined after 30 milli seconds The name of the current thread is Thread-0 The name of the current thread is Thread-0 Is the current thread alive? true Is the current thread alive? true
코드 설명
Demo라는 클래스가 Runnable 인터페이스를 구현하고 있습니다. run() 메서드 내부에서는 Thread.currentThread()를 통해 현재 실행 중인 스레드를 가져온 뒤, 그 이름과 생존 여부(isAlive())를 출력합니다.
main 메서드에서는 Demo 인스턴스를 기반으로 새로운 스레드 객체를 생성하고, start() 메서드를 호출하여 스레드를 실행합니다. 이어서 join(30)을 호출하여 최대 30밀리초 동안 해당 스레드의 종료를 기다린 후, 스레드의 이름과 생존 여부 관련 메시지를 화면에 출력합니다.
join() 메서드의 주요 특징
- 실행 순서 보장: 선행 스레드의 작업이 반드시 먼저 완료되도록 순서를 제어할 수 있습니다.
- 타임아웃 지원:
join(long millis),join(long millis, int nanos)형태로 최대 대기 시간을 지정할 수 있습니다. - 인터럽트 처리: 대기 중에 다른 스레드가 인터럽트를 발생시키면
InterruptedException이 던져지므로 적절한 예외 처리가 필요합니다.