스레드의 우선순위(priority of thread)
- 작업의 중요도에 따라 스레드의 우선순위를 다르게 하여 특정 스레드가 더 많은 작업 시간을 갖도록 할 수 있다.
- 메인 스레드의 기본 우선순위는 5이다.
🌳 기본 우선순위로 출력하기
public class ThreadTest05 {
public static void main(String[] args) {
Thread th1 = new UpperThread();
Thread th2 = new LowerThread();
System.out.println("th1의 현재 우선순위 : " + th1.getPriority());
System.out.println("th2의 현재 우선순위 : " + th2.getPriority());
th1.start();
th2.start();
}
}
// 대문자를 출력하는 스레드
class UpperThread extends Thread {
@Override
public void run() {
for (char c = 'A'; c <= 'Z'; c++) {
System.out.print(c);
for (long i = 1; i <= 500_000_000L; i++) {
}
// sleep은 아예 일시정지가 되는 것이기 때문에 제어권이 넘어감
// 따라서 sleep 대신 반복문을 사용하여 공회전하게 만든 것
}
}
}
// 소문자를 출력하는 스레드
class LowerThread extends Thread {
@Override
public void run() {
for (char c = 'a'; c <= 'z'; c++) {
System.out.print(c);
for (long i = 1; i <= 500_000_000L; i++) {
}
}
}
}
// th1의 현재 우선순위 : 5
// th2의 현재 우선순위 : 5
// AaBbCcDdEeFfGgHhIiJjKkLlMmNnOPoQpRqSrTsUtVuWvXwYxZyz
- 우선순위가 같기 때문에 번갈아 출력됨
🌳 우선순위를 변경하여 출력하기
- setPriority(), getPriority() 메소드를 이용한다.
public class ThreadTest05 {
public static void main(String[] args) {
Thread th1 = new UpperThread();
Thread th2 = new LowerThread();
th1.setPriority(9);
th2.setPriority(2);
System.out.println("th1의 현재 우선순위 : " + th1.getPriority());
System.out.println("th2의 현재 우선순위 : " + th2.getPriority());
th1.start();
th2.start();
}
}
- CPU의 코어가 좋으면 우선순위를 변경하여도 큰 차이 없이 출력됨