자바 스레드 우선순위란?
멀티스레딩 환경에서는 스레드 스케줄러(Thread Scheduler)가 각 스레드의 우선순위를 기준으로 CPU 자원을 배분합니다. 자바의 모든 스레드는 생성 시점부터 기본 우선순위를 부여받으며, JVM(Java Virtual Machine)이 이 값을 지정하거나 개발자가 직접 명시적으로 설정할 수도 있습니다.
자바에서 스레드 우선순위 값은 1부터 10까지(양 끝값 포함)의 정수 범위를 가지며, 다음과 같은 세 가지 static 상수가 제공됩니다.
- MAX_PRIORITY – 스레드가 가질 수 있는 최대 우선순위로, 기본값은 10입니다.
- NORM_PRIORITY – 스레드에 기본적으로 부여되는 우선순위로, 기본값은 5입니다.
- MIN_PRIORITY – 스레드가 가질 수 있는 최소 우선순위로, 기본값은 1입니다.
getPriority()와 setPriority() 메서드
getPriority() 메서드는 해당 스레드에 설정된 현재 우선순위 값을 반환합니다.
setPriority() 메서드는 특정 스레드의 우선순위를 변경하는 데 사용되며, 인자로 전달된 값이 1보다 작거나 10보다 크면 IllegalArgumentException을 발생시킵니다.
참고로 스레드 우선순위는 운영체제 스케줄러에 전달되는 하나의 '힌트'일 뿐이므로, 실제 실행 순서가 항상 우선순위대로 보장되는 것은 아니며 플랫폼에 따라 동작이 달라질 수 있다는 점을 유의해야 합니다.
예제 코드
import java.lang.*;
public class Demo extends Thread {
public void run(){
System.out.println("Now, inside the run method");
}
public static void main(String[] args){
Demo my_thr_1 = new Demo();
Demo my_thr_2 = new Demo();
System.out.println("The thread priority of first thread is : " + my_thr_1.getPriority());
System.out.println("The thread priority of second thread is : " + my_thr_2.getPriority());
my_thr_1.setPriority(5);
my_thr_2.setPriority(3);
System.out.println("The thread priority of first thread is : " + my_thr_1.getPriority());
System.out.println("The thread priority of second thread is : " + my_thr_2.getPriority());
System.out.print(Thread.currentThread().getName());
System.out.println("The thread priority of main thread is : "
+ Thread.currentThread().getPriority());
Thread.currentThread().setPriority(10);
System.out.println("The thread priority of main thread is : "
+ Thread.currentThread().getPriority());
}
}
실행 결과
The thread priority of first thread is : 5 The thread priority of second thread is : 5 The thread priority of first thread is : 5 The thread priority of second thread is : 3 mainThe thread priority of main thread is : 5 The thread priority of main thread is : 10
코드 분석
- Demo 클래스는 기반 클래스인
Thread를 상속받으며, 스레드 실행 시 호출되는run()메서드를 오버라이드하여 안내 메시지를 출력하도록 정의되어 있습니다. main()함수 내부에서 Demo 클래스의 인스턴스 두 개를 생성한 뒤,getPriority()를 호출하여 각 스레드의 초기 우선순위를 확인하고 콘솔에 출력합니다.- 초기 우선순위는 두 스레드 모두 기본값인 5(NORM_PRIORITY)로 표시됩니다.
- 이후
setPriority()메서드를 통해 첫 번째 스레드에는 5, 두 번째 스레드에는 3을 할당하고, 변경된 값을 다시 콘솔에 출력합니다. getName()메서드를 사용하면 현재 실행 중인 스레드의 이름(여기서는 'main')을 화면에 출력할 수 있습니다.- 마지막으로 메인 스레드의 우선순위를
setPriority(10)으로 변경한 결과, 우선순위가 5에서 10으로 바뀌어 출력되는 것을 확인할 수 있습니다.