Java 메인 스레드(Main thread)

이진호·2022년 9월 14일
0

Java Multithreading

목록 보기
3/3
post-thumbnail

Java는 다중 스레드 프로그래밍을 지원합니다. 다중 스레드는 2개 이상의 스레드로 구성되며, 스레드는 별도의 실행 경로를 가집니다.

자바 프로그램 시작과 동시에 하나의 스레드가 즉시 동작하게 됩니다. 이를 메인 스레드(Main thread)라도 합니다.

메인 스레드는 아래와 같은 속성을 가집니다.

  • 메인 스레드로부터 다른 자식 스레드(Child thread)가 생성됩니다.
  • 다양한 종료 작업을 수행하기 때문에 대체로 마지막으로 실행 종료되는 스레드여야 합니다.

Java 메인 스레드(Main thread)

메인 스레드 제어

메인 스레드는 프로그램의 실행과 동시에 생성됩니다. 메인 스레드를 제어하기 위해선 이것의 참조를 얻어야 합니다. 호출된 스레드의 참조를 반환하는Thread.currentThread() 명령어를 통해 참조를 얻을 수 있습니다. 메인 스레드의 기본 우선 순위(default priority)는 5이며, 이는 부모 스레드로부터 자식 스레드로 상속됩니다.

// Java program to control the Main Thread
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Class 1
// Main class extending thread class
public class Test extends Thread {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Getting reference to Main thread
        Thread t = Thread.currentThread();
 
        // Getting name of Main thread
        System.out.println("Current thread: "
                           + t.getName());
 
        // Changing the name of Main thread
        t.setName("Geeks");
        System.out.println("After name change: "
                           + t.getName());
 
        // Getting priority of Main thread
        System.out.println("Main thread priority: "
                           + t.getPriority());
 
        // Setting priority of Main thread to MAX(10)
        t.setPriority(MAX_PRIORITY);
 
        // Print and display the main thread priority
        System.out.println("Main thread new priority: "
                           + t.getPriority());
 
        for (int i = 0; i < 5; i++) {
            System.out.println("Main thread");
        }
 
        // Main thread creating a child thread
        Thread ct = new Thread() {
            // run() method of a thread
            public void run()
            {
 
                for (int i = 0; i < 5; i++) {
                    System.out.println("Child thread");
                }
            }
        };
 
        // Getting priority of child thread
        // which will be inherited from Main thread
        // as it is created by Main thread
        System.out.println("Child thread priority: "
                           + ct.getPriority());
 
        // Setting priority of Main thread to MIN(1)
        ct.setPriority(MIN_PRIORITY);
 
        System.out.println("Child thread new priority: "
                           + ct.getPriority());
 
        // Starting child thread
        ct.start();
    }
}
 
// Class 2
// Helper class extending Thread class
// Child Thread class
class ChildThread extends Thread {
 
    @Override public void run()
    {
 
        for (int i = 0; i < 5; i++) {
 
            // Print statement whenever child thread is
            // called
            System.out.println("Child thread");
        }
    }
}

메인 스레드와 main() 메소드의 관계

각각의 프로그램에서 메인 스레드는 JVM(Java Virtual Machine)으로부터 생성됩니다. 메인 스레드는 먼저 main() 메소드의 존재를 확인 한 다음, class를 초기화 합니다. JDK 6 부터, main() 메소드는 Java 응용 프로그램에서 필수입니다.

메인 스레드 교착상태(deadlock)

// Java program to demonstrate deadlock
// using Main thread
 
// Main class
public class GFG {
 
  // Main driver method
  public static void main(String[] args) {
 
    // Try block to check for exceptions
    try {
 
      // Print statement
      System.out.println("Entering into Deadlock");
 
      // Joining the current thread
      Thread.currentThread().join();
 
      // This statement will never execute
      System.out.println("This statement will never execute");
    }
 
    // Catch block to handle the exceptions
    catch (InterruptedException e) {
 
      // Display the exception along with line number
      // using printStackTrace() method
      e.printStackTrace();
    }
  }
}

Thread.currentThread().join() 명령어는 자식 스레드가 종료될때까지 대기시키는 명령어입니다. 위 코드에서 메인 스레드에서 이를 실행시켰는데, 메인 스레드의 자식 스레드가 없는 상황이므로, 메인 스레드 본인이 종료될 때까지 대기를 하게 됩니다. 이것은 아무 의미 없는 교착상태(deadlock)를 유발하게 됩니다.

출처

1개의 댓글

comment-user-thumbnail
2023년 12월 21일

땡큐입니다

답글 달기