Computer >> 컴퓨터 >  >> 프로그램 작성 >> Java

다중 스레딩에서 Java 스레드 우선 순위

<시간/>

다중 스레딩 상황에서 스레드 스케줄러는 우선 순위에 따라 특정 프로세스에 스레드를 할당합니다. Java 스레드에는 미리 할당된 우선 순위가 있습니다. 이 외에도 Java 가상 머신은 스레드에 우선 순위를 할당하거나 프로그래머가 명시적으로 지정할 수도 있습니다. 스레드의 우선 순위 값 범위는 1에서 10(포함) 사이입니다. 우선 순위와 관련된 세 가지 정적 변수는 -

  • MAX_PRIORITY - 스레드가 가지는 최대 우선순위로, 기본값은 10입니다.

  • NORM_PRIORITY - 스레드가 가지는 기본 우선순위로, 기본값은 5입니다.

  • MIN_PRIORITY - 스레드가 갖는 최소 우선순위로, 기본값은 1입니다.

Java의 '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 first 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 first 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 first thread is : 5
The thread priority of first thread is : 5
The thread priority of first thread is : 3
The thread priority of main thread is : 5
The thread priority of main thread is : 10

Demo라는 클래스는 기본 클래스 Thread에서 상속합니다. 'run' 기능이 정의되고 관련 메시지가 정의됩니다. 메인 함수에서 2개의 Demo 클래스 인스턴스가 생성되고 'getPriority' 함수를 호출하여 우선 순위를 찾습니다.

콘솔에 인쇄되어 있습니다. 다음으로 'setPriority' 함수를 사용하여 데모 인스턴스에 우선 순위를 할당합니다. 출력이 콘솔에 표시됩니다. 스레드의 이름은 'getName' 함수의 도움으로 화면에 인쇄됩니다.