Files
java-examples/docs/Concurrency/01_Thread.md

7.7 KiB

자바의 Thread 클래스와 관련된 주요 메서드들을 표로 정리하고, 각 메서드에 대한 설명과 예시를 포함한 글을 작성하겠습니다. 아래는 요청하신 내용입니다.


자바 Thread 관련 메서드 표

메서드명 반환 타입 설명
start() void 스레드를 시작하며, run() 메서드를 호출하여 실행 준비 상태로 만듦
run() void 스레드가 실행할 작업을 정의 (직접 호출 시 스레드 생성 없이 현재 스레드에서 실행)
sleep(long millis) void 지정된 시간(밀리초) 동안 스레드를 일시 정지 (정적 메서드)
join() void 해당 스레드가 종료될 때까지 현재 스레드가 기다림
interrupt() void 스레드에 인터럽트를 발생시켜 작업을 중단 요청
isAlive() boolean 스레드가 실행 중인지 여부를 확인
setPriority(int n) void 스레드의 우선순위를 설정 (1~10 사이 값)
getPriority() int 스레드의 현재 우선순위를 반환
yield() void 현재 스레드가 다른 스레드에게 실행 기회를 양보 (정적 메서드)
currentThread() Thread 현재 실행 중인 스레드 객체를 반환 (정적 메서드)

Thread 메서드 설명 및 예시

자바에서 스레드는 멀티태스킹을 구현하는 데 필수적인 요소입니다. Thread 클래스와 Runnable 인터페이스를 통해 스레드를 생성하고 관리할 수 있으며, 위 표에 정리된 메서드들은 스레드의 생명주기와 동작을 제어하는 데 사용됩니다. 아래에서는 주요 메서드들을 예시와 함께 설명하겠습니다.

1. start()run()

  • start(): 새로운 스레드를 생성하고 실행 가능한 상태로 만들어 run() 메서드를 호출합니다.
  • run(): 실제 스레드가 수행할 작업을 정의합니다. 단, run()을 직접 호출하면 새로운 스레드가 생성되지 않고 현재 스레드에서 실행됩니다.
class MyThread extends Thread {
    public void run() {
        System.out.println("스레드 실행 중: " + Thread.currentThread().getName());
    }
}

public class ThreadExample {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start(); // 새로운 스레드 생성 및 실행
        // thread.run(); // 이렇게 호출하면 메인 스레드에서 실행됨
    }
}
  • 출력: 스레드 실행 중: Thread-0

2. sleep(long millis)

  • 지정된 시간 동안 현재 스레드를 일시 정지합니다. 다른 스레드에게 CPU를 양보하며, InterruptedException을 처리해야 합니다.
public class SleepExample {
    public static void main(String[] args) {
        try {
            System.out.println("2초 후에 깨어납니다.");
            Thread.sleep(2000); // 2초 대기
            System.out.println("깨어났습니다!");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
  • 출력:
    2초 후에 깨어납니다.
    (2초 대기 후)
    깨어났습니다!
    

3. join()

  • 다른 스레드가 종료될 때까지 현재 스레드가 기다리도록 합니다. 작업 순서를 보장할 때 유용합니다.
class WorkerThread extends Thread {
    public void run() {
        System.out.println("작업 시작");
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("작업 완료");
    }
}

public class JoinExample {
    public static void main(String[] args) throws InterruptedException {
        WorkerThread worker = new WorkerThread();
        worker.start();
        worker.join(); // worker 스레드가 끝날 때까지 대기
        System.out.println("메인 스레드 계속 진행");
    }
}
  • 출력:
    작업 시작
    (1초 후)
    작업 완료
    메인 스레드 계속 진행
    

4. interrupt()

  • 스레드에 인터럽트를 발생시켜 작업을 중단하도록 요청합니다. sleep()이나 wait() 중인 스레드는 InterruptedException을 발생시킵니다.
class InterruptThread extends Thread {
    public void run() {
        try {
            while (true) {
                System.out.println("작업 중...");
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            System.out.println("인터럽트 발생! 종료합니다.");
        }
    }
}

public class InterruptExample {
    public static void main(String[] args) throws InterruptedException {
        InterruptThread thread = new InterruptThread();
        thread.start();
        Thread.sleep(2000); // 2초 후 인터럽트
        thread.interrupt();
    }
}
  • 출력:
    작업 중...
    작업 중...
    작업 중...
    인터럽트 발생! 종료합니다.
    

5. setPriority(int n)getPriority()

  • 스레드의 우선순위를 설정하고 확인합니다. 우선순위는 1(최저)에서 10(최고)까지이며, 기본값은 5입니다.
public class PriorityExample {
    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> System.out.println("Thread 1 실행"));
        Thread thread2 = new Thread(() -> System.out.println("Thread 2 실행"));

        thread1.setPriority(Thread.MIN_PRIORITY); // 1
        thread2.setPriority(Thread.MAX_PRIORITY); // 10

        System.out.println("Thread 1 우선순위: " + thread1.getPriority());
        System.out.println("Thread 2 우선순위: " + thread2.getPriority());

        thread1.start();
        thread2.start();
    }
}
  • 출력 (실행 순서는 보장되지 않음):
    Thread 1 우선순위: 1
    Thread 2 우선순위: 10
    Thread 2 실행
    Thread 1 실행
    

6. yield()

  • 현재 스레드가 다른 스레드에게 실행 기회를 양보합니다. CPU 스케줄링에 따라 결과가 달라질 수 있습니다.
class YieldThread extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println(getName() + " 실행 중");
            Thread.yield(); // 다른 스레드에게 양보
        }
    }
}

public class YieldExample {
    public static void main(String[] args) {
        Thread thread1 = new YieldThread();
        Thread thread2 = new YieldThread();
        thread1.start();
        thread2.start();
    }
}
  • 출력 (순서 무작위):
    Thread-0 실행 중
    Thread-1 실행 중
    Thread-0 실행 중
    Thread-1 실행 중
    ...
    

결론

자바의 Thread 클래스는 스레드 생성, 실행, 제어를 위한 다양한 메서드를 제공합니다. start()run()으로 스레드를 시작하고, sleep(), join(), interrupt()로 동작을 제어하며, setPriority()yield()로 스케줄링을 조정할 수 있습니다. 위 예시를 통해 각 메서드의 동작을 이해하고, 실제 멀티스레드 프로그래밍에 적용해 보세요!