정의
- 이름 그래도 스레드 작업의 중요도에 따라서 부여되는 순위이다.
- jvm에서 정해주기도 하지만 프로그래머가 명시적으로 정의해 줄 수 있다.
- java에선 1~10까지 정도의 우선 순위를 두고 지정한다. 아래와 같이 주로 3가지 순위를 가진다.
- 기본 우선 순위(NORM_PRIORITY) : 5
- 최소 우선 순위(MIN_PRIORITY) : 1
- 최대 우선 순위(MAX_PRIOROTY) : 10
활용 방법
- JAVA에서는 이러한 스레드의 우선순위를 지정해주기 위해 Thread.class에선 아래와 같은 상수값을 정의해두고 있다.
- public static int NORM_PRIORITY
- public static int MIN_PRIORITY
- public static int MAX_PRIORITY
- 또한 우선순위를 가져오고 설정하는 메소드는 아래와 같다.
Thread thread1 = new Thread(task1);
thread1.setPriority(8);
- 스레드 우선순위는 setPriority() 메서드를 설정할 수 있다.
Thread thread1 = new Thread(task1);
thread1.setPriority(8);
- getPriority() 메서드로 우선순위를 반환할 수 있다.
public class Main {
public static void main(String[] args) {
Runnable task1 = () -> {
for (int i = 0; i < 100; i++) {
System.out.print("$");
}
};
Runnable task2 = () -> {
for (int i = 0; i < 10; i++) {
System.out.print("*");
}
};
Runnable task3 = () -> {
for (int i = 0; i < 10; i++) {
System.out.print("x");
}
};
Thread thread1 = new Thread(task1);
thread1.setPriority(1);
int threadPriority = thread1.getPriority();
System.out.println("threadPriority = " + threadPriority);
Thread thread2 = new Thread(task2);
thread2.setPriority(2);
Thread thread3 = new Thread(task3);
thread2.setPriority(3);
thread1.start();
thread2.start();
thread3.start();
}
}
- 주의할 점은 스레드의 우선순위는 먼저 종료될 가능성이 높아지는 것일 뿐 무조건 먼저 종료 되는것은 아니다. 스레드에 따라서 우선순위가 아무리 높아도 낮은 순위의 스레드보다 해야할 연산량이 많으면 먼저 시작되어도 늦게 끝날 수 있다.

- 100번 반복해야하는 task 1에 비해 task 2와 task 3는 우선순위가 낮음에도 10번만 반복하면 되었기에 task 1이 종료되기도 전에 끝났고 그에 비해 task 1은 그 둘이 종료 되었음에도 종료되지 않았다.
마무리
- 우선순위까지 살펴보았는데 실제 프로젝트에서 사용한다면 어떻게 사용할지 좀 더 세심한 컨벤션이 필요하다는 생각이 들었다.
출처
https://handr95.tistory.com/37