Java 스레드(Thread) Thread 우선순위
Thread 우선순위
자바 스레드에서는 스레드에 우선순위를 부여하여 높은 우선순위를 가진 스레드에게 실행할 우선권을 주어 실행시킬 수 있다.
Thread 클래스 내부에서는 우선순위를 정하기 위해 다음과 같은 상수를 제공하고 있다.
/**
* The minimum priority that a thread can have.
*/
public final static int MIN_PRIORITY = 1;
/**
* The default priority that is assigned to a thread.
*/
public final static int NORM_PRIORITY = 5;
/**
* The maximum priority that a thread can have.
*/
public final static int MAX_PRIORITY = 10;
최하 1부터 최상 10까지 부여가 가능하고 기본값으로는 5가 부여된다.
JVM에서는 스레드를 수행하고 끝나면 다음에는 실행 가능한 스레드 중에 한 개를 골라 실행하게 되는데 우선순위가 높을수록 실행될 확률이 높아진다. 우선순위가 같을 때에는 스레드 스케줄러의 기준에 의하여 실행될 스레드가 결정된다.
예제 1) Thread 우선순위 설정
다음 예제는 Thread 2개에 우선순위를 최상과 최하로 설정했다.
package com.devkuma.tutorial.thread;
public class MyThreadPriority extends Thread {
public MyThreadPriority(String name) {
super(name);
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(super.getName() + " thread. i=" + i);
}
}
public static void main(String[] args) {
MyThreadPriority thread1 = new MyThreadPriority("first");
MyThreadPriority thread2 = new MyThreadPriority("second");
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
thread1.start();
thread2.start();
}
}
실행 결과:
second thread. i=0
second thread. i=1
first thread. i=0
second thread. i=2
first thread. i=1
second thread. i=3
second thread. i=4
second thread. i=5
second thread. i=6
second thread. i=7
second thread. i=8
second thread. i=9
first thread. i=2
first thread. i=3
first thread. i=4
first thread. i=5
first thread. i=6
first thread. i=7
first thread. i=8
first thread. i=9
결과에서 보이듯이 first보다는 second가 먼저 더 많이 실행된 것을 확인할 수 있다.