티스토리 뷰

[JAVA]/JAVA

<Thread> Priority 지정하기

춘햄 2021. 3. 31. 11:50

각 스레드 객체를 생성한 뒤 어느 스레드를 우선으로 실행할 지 지정해줄 수 있다.

그러나, 예시에서 사용할 코드는 각각 스레드의 작업량이 그렇게 많지 않아서 뚜렷한 우선순위 차이를 보기는 힘들다.

그냥 priority 를 이렇게 지정하는구나...라고 생각하면 될 거 같다.

 


○PriorityThread:

package com.choonham;

public class PriorityThread extends Thread {

	public PriorityThread() {
		// TODO Auto-generated constructor stub
	}
	public void run() {
		int i = 0;
		System.out.println(this.getName() + "[우선권:" + this.getPriority() + "] 시작");
		
		while(i < 10000) {
			i ++;
			try {
				this.sleep(1);
				
			}catch(InterruptedException e ) {
				System.out.println(e.getMessage());
			}
		}
		
		System.out.println(this.getName() + "[우선권:" + this.getPriority() + "] 종료");
	}
	
}

○MainClass:

package com.choonham;

public class MainClass {

	public static void main(String[] args) {
		PriorityThread p1 = new PriorityThread();
		PriorityThread p2 = new PriorityThread();
		PriorityThread p3 = new PriorityThread();
		
		p1.setPriority(Thread.MAX_PRIORITY);  // 1(MIN) ~ 10(MAX)의 값
		p2.setPriority(Thread.NORM_PRIORITY);
		p3.setPriority(Thread.MIN_PRIORITY); 
		
		p1.start();
		p2.start();
		p3.start();
	}

}

○Output:

 

*각 스레드가 할당받은 데이터 값이 많아질 경우 더 뚜렷한 결과를 얻을 수 있다.*

Comments