본문 바로가기
강의 자료/고성능을 강조한 Java 멀티스레딩, 병행성 및 병렬 실행 프로그래밍

섹션 2: 스레딩 기초 - 스레드 생성 (스레드의 기능 + 스레드 상속)

by 토니당 2025. 5. 18.
반응형
반응형

💡 Java에서 Thread 생성 실행 정리

🔄 1️⃣ Thread 생성

  • Java에서 모든 스레드 관련 속성메서드Thread 클래스에 정의되어 있습니다.
  • Thread생성할 때는 Thread 클래스 객체생성합니다.
  • 생성자에 Runnable 인터페이스전달해야 합니다.
public class Main {

    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // Code that will run in a new thread.

            }
        });
    }
}

 


🚀 2️⃣ Thread 실행

  • 생성된 Thread 객체는 start() 메서드를 호출해야 실행됩니다.
  • thread.start();JVM새로운 스레드를 생성하여 운영체제에 전달합니다.
thread.start();

 

👁️ 3️⃣ 실행 중인 스레드 확인

  • Thread.currentThread().getName()으로 현재 실행 중인 스레드 이름확인할 있습니다.
System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName() + "before starting ");
        
thread.start();

System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName() + "after starting ");

 

 


📝 4️⃣ 최종 코드 실행 결과

 

package thread.create1;

public class Main {

    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // Code that will run in a new thread.
                // 1
                System.out.println("We are now in thread " + Thread.currentThread().getName());
            }
        });
        
        //2
        System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName() + "before starting ");
        
        thread.start();
        
        // 3
        System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName() + "after starting ");
    }
}

 

실행 결과 : 

 

실행 순서:

  1. 메인 스레드에서 "before starting" 출력
  2. thread.start();JVM새로운 스레드 생성
  3. 메인 스레드에서 "after starting" 출력
  4. 새롭게 생성된 쓰레드에서 "We are now in thread..." 출력

💡 이유:

  • thread.start();비동기적으로 실행되기 때문에, 메인 스레드는 계속 진행하며 2번과 3번이 먼저 출력됩니다.
  • 이후에 새로운 스레드가 실행되면서 4번이 출력됩니다.

⚙️ 5️⃣ Thread 우선순위 설정

  • 스레드의 이름우선순위설정할 있습니다.
  • 우선순위 설정 → thread.setPriority(Thread.MAX_PRIORITY);
   Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                // Code that will run in a new thread.
                // 1
                System.out.println("We are now in thread " + Thread.currentThread().getName());
                System.out.println("Current thread priority is " + Thread.currentThread().getPriority());
            }
        });

        thread.setName("New worker thread");
        
        thread.setPriority(Thread.MAX_PRIORITY);

 

  • MAX_PRIORITY: 10
  • MIN_PRIORITY: 1
  • NORM_PRIORITY: 5

우선순위 설정은 복잡한 멀티스레드 환경에서 실행 순서와 속도에 영향을 미칠 있습니다.

 

위 코드를 실행해도 동일한 순서가 나온다. 

아직까지는 수행차이가 없지만 추후 복잡한 멀티쓰레드 환경에 코드를 실행하고 우선순위등 결정해야할때 아주 중요한 역할을 한다. 

 

실행 결과 : 

 

 

💡 Thread 생성 방법 2: Thread 클래스 상속


🔄 1️⃣ Thread 클래스 상속하기

  • 기존에 사용한 Runnable 인터페이스 구현 대신, Thread 클래스를 상속하여 직접 스레드를 생성할 있습니다.
  • Thread 클래스는 이미 Runnable 인터페이스를 구현하고 있기 때문에, run() 메서드만 오버라이드하면 됩니다.

✍️ 2️⃣ 코드 예시

public class Main {

    public static void main(String[] args) {
        Thread thread = new NewThread();

        thread.start();
    }
    
    public static class NewThread extends Thread  {
        
        @Override
        public void run() {
            System.out.println("Thread.currentThread().getName() = " + Thread.currentThread().getName());
        }
    }
}

 

 

🚀 4️⃣ 특징 장점

특징설명
✔️ 코드가 간결해짐 Runnable따로 구현할 필요 없이 run()오버라이드하면
✔️ 명확한 클래스 정의 Thread 클래스를 상속받기 때문에 명확한 역할을 가진 클래스 생성
✔️ 추가 메서드 사용 가능 Thread 클래스의 다양한 메서드 (getName(), getId(), sleep())바로 사용 가능
 

5️⃣ 단점

  • Java단일 상속만 허용하므로, 다른 클래스를 상속받고 싶다면 사용할 없습니다.
  • 경우 Runnable 인터페이스 구현 방식유연합니다.

🔍 6️⃣ 결론

  • Thread 상속 방식: 코드가 간단하고 명확하지만, 단일 상속 제약이 있음
  • Runnable 구현 방식: 다중 상속이 필요할 유리함
반응형