Computer >> Máy Tính >  >> Lập trình >> Java

Tầm quan trọng của Ưu tiên luồng trong Java?


Trong các ứng dụng đa luồng, mỗi luồng được gán một mức độ ưu tiên. Bộ xử lý được chỉ định cho luồng bởi trình lập lịch luồng dựa trên mức độ ưu tiên của nó, tức là luồng có mức độ ưu tiên cao nhất được chỉ định cho bộ xử lý trước, v.v. Mức độ ưu tiên mặc định của một chuỗi có giá trị là ' 5' . Chúng tôi có thể nhận được mức độ ưu tiên của một chuỗi bằng cách sử dụng getPosystem () phương thức của lớp Thread.

Ba giá trị tĩnh được xác định trong Chủ đề lớp cho mức độ ưu tiên của một luồng

MAX_PRIORITY

Đây là mức độ ưu tiên của chuỗi tối đa với giá trị là 10 .

NORM_PRIORITY

Đây là mặc định mức độ ưu tiên của chuỗi có giá trị là 5 .

MIN_PRIORITY

Đây là mức độ ưu tiên của chuỗi tối thiểu với giá trị là 1 .

Cú pháp

public final int getPriority()

Ví dụ

public class ThreadPriorityTest extends Thread {
   public static void main(String[]args) {
      ThreadPriorityTest thread1 = new ThreadPriorityTest();
      ThreadPriorityTest thread2 = new ThreadPriorityTest();
      ThreadPriorityTest thread3 = new ThreadPriorityTest();
      System.out.println("Default thread priority of thread1: " + thread1.getPriority());
      System.out.println("Default thread priority of thread2: " + thread2.getPriority());
      System.out.println("Default thread priority of thread3: " + thread3.getPriority());
      thread1.setPriority(8);
      thread2.setPriority(3);
      thread3.setPriority(6);
      System.out.println("New thread priority of thread1: " + thread1.getPriority());
      System.out.println("New thread priority of thread2: " + thread2.getPriority());
      System.out.println("New thread priority of thread3: " + thread3.getPriority());
   }
}

Đầu ra

Default thread priority of thread1: 5
Default thread priority of thread2: 5
Default thread priority of thread3: 5
New thread priority of thread1: 8
New thread priority of thread2: 3
New thread priority of thread3: 6