스레드가 끝날 때까지 기다리기

Copyright (c) 2015-, All Rights Reserved by Kwanghoon Choi
(아래 자바 프로그래밍 강의 교재의 내용을 자유롭게 이용하되 다른 웹 사이트 등을 통한 배포를 금합니다.)

 

3. Java 스레드 (Thread)의  실행이 끝날 때까지 기다리기

Thread 클래스의 join 메소드는 호출 객체로 지정된 스레드의  실행이 끝날 때까지 기다렸다 리턴하도록 정의되어 있다. Java 응용 프로그램을 작성해서 실행하면 기본적으로 메인 스레드를 만들어 그 위에서 자바 가상기계를 실행하고 main 메소드가 호출된다. main 메소드에서 새로운 스레드를 만들어 작업을 독립적으로 진행하고 그 작업이 끝나면 종료 메시지를 출력하도록 프로그램을 구성해보자.

Thread t1 = new MyThread();
t1.start();
Thread t2 = new Thread( new MyImplementation() );
t2.start();

t1.join(); // t1 스레드의 실행이 끝나면 리턴
t2.join(); // t2 스레드의 실행이 끝나면 리턴

System.out.println("This is the end of ThreadTest");

만일 t1.join()이나 t2.join() 메소드를 호출하지 않으면 두 스레드가 모두 실행되거나 또는 둘 중 하나가 여전히 실행 중임에도 불구하고 "This is the end of ThreadTest" 메시지를 출력할 수 있다. 지금까지 논의한 내용을 종합해서 프로그램을 작성해보면 다음과 같다.

package com.example.java;

public class ThreadTest {

    public static void main(String[] arg )
    {
        Thread t1 = new MyThread();
        t1.start(); // 스레드를 하나 만들어 독립적으로 실행
        Thread t2 = new Thread( new MyImplementation() );
        t2.start(); // 두번째 스레드를 만들어 실행

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("This is the end of ThreadTest");
    }
}

class MyThread extends Thread {
    public void run() {
        for (int i=0; i<5; i++) {
            System.out.println("MyThread");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class MyImplementation implements Runnable {
    public void run() {
        for (int i=0; i<5; i++) {
            System.out.println("MyImplementation");
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

Thread 클래스의 interrupt 메소드를 호출하여 지정한 스레드에서 예외 InterruptedException을 발생시킬 수 있다.

public static void main(String[] arg )
{
    Thread t1 = new MyThread();
    t1.start(); // 스레드를 하나 만들어 독립적으로 실행
    Thread t2 = new Thread( new MyImplementation() );
    t2.start(); // 두번째 스레드를 만들어 실행

    try {
        t1.interrupt();
        t2.interrupt();
        t1.join();
        t2.join();
   } catch (InterruptedException e) {
        e.printStackTrace();
    }

    System.out.println("This is the end of ThreadTest");
}

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *