Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Tầm quan trọng của Thread Priority trong Java

Thread Priority

Mỗi thread có độ ưu tiên (priority) từ 1 (MIN) đến 10 (MAX). Mặc định = 5 (NORM_PRIORITY). Thread scheduler (thường là OS) ưu tiên cấp CPU cho thread priority cao hơn.

Hằng số trong Thread class

  • MIN_PRIORITY = 1
  • NORM_PRIORITY = 5 (default)
  • MAX_PRIORITY = 10

Phương thức

  • getPriority() – lấy priority hiện tại
  • setPriority(int) – set priority (1-10), ném IllegalArgumentException nếu ngoài phạm vi

Ví dụ


public class ThreadPriorityDemo extends Thread {
    public static void main(String[] args) {
        ThreadPriorityDemo t1 = new ThreadPriorityDemo();
        ThreadPriorityDemo t2 = new ThreadPriorityDemo();
        ThreadPriorityDemo t3 = new ThreadPriorityDemo();

        System.out.println("Default priority t1: " + t1.getPriority()); // 5
        System.out.println("Default priority t2: " + t2.getPriority()); // 5
        System.out.println("Default priority t3: " + t3.getPriority()); // 5

        t1.setPriority(8);
        t2.setPriority(3);
        t3.setPriority(6);

        System.out.println("New priority t1: " + t1.getPriority()); // 8
        System.out.println("New priority t2: " + t2.getPriority()); // 3
        System.out.println("New priority t3: " + t3.getPriority()); // 6
    }
}

Kết quả

Default priority t1: 5
Default priority t2: 5
Default priority t3: 5
New priority t1: 8
New priority t2: 3
New priority t3: 6

Chú ý: Priority chỉ là gợi ý cho scheduler, không đảm bảo thứ tự thực thi chính xác. Tránh phụ thuộc vào priority cho logic đúng đắn (correctness). Dùng synchronization, concurrent utilities thay thế.