PHpullh
학습 라이브러리/Java/Thread vs Runnable

JAVA · 비동기/동시성

Thread vs Runnable

스레드 생성 방법과 Thread 상속 vs Runnable 구현의 차이입니다.

비동기/동시성중급ThreadRunnable스레드start

핵심 설명

스레드 생성 방법과 Thread 상속 vs Runnable 구현의 차이입니다.

Java code

public class ThreadBasics {
    // 방법 1: Thread 상속 (권장하지 않음)
    static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.printf("[%s] Thread 상속%n",
                Thread.currentThread().getName());
        }
    }

    // 방법 2: Runnable 구현 (권장)
    static class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.printf("[%s] Runnable 구현%n",
                Thread.currentThread().getName());
        }
    }

    public static void main(String[] args) throws InterruptedException {
        // Thread 상속
        new MyThread().start();

        // Runnable
        new Thread(new MyRunnable()).start();

        // 람다 (가장 간결)
        Thread t = new Thread(() ->
            System.out.println("람다 스레드!"));
        t.start();
        t.join(); // 스레드 종료 대기

        // 스레드 속성
        Thread current = Thread.currentThread();
        System.out.println("이름: " + current.getName());
        System.out.println("우선순위: " + current.getPriority());
        System.out.println("데몬: " + current.isDaemon());
    }
}

학습 팁

Runnable을 사용하면 다른 클래스를 상속할 수 있고, ExecutorService에도 제출할 수 있어 유연합니다.

주의할 점

run()을 직접 호출하면 새 스레드가 아닌 현재 스레드에서 실행됩니다. 반드시 start()를 호출하세요.

자주 묻는 질문

Thread vs Runnable란 무엇인가요?

스레드 생성 방법과 Thread 상속 vs Runnable 구현의 차이입니다.

Thread vs Runnable 학습 시 주의할 점은 무엇인가요?

run() 을 직접 호출하면 새 스레드가 아닌 현재 스레드에서 실행됩니다. 반드시 start() 를 호출하세요.