ความสำคัญของ Thread Priority
Thread scheduler กำหนดลำดับการรัน thread ตาม priority (1-10) ค่าสูง = โอกาสรันมากกว่า แต่ไม่รับประกัน ลำดับการทำงานจริง ขึ้นกับ OS และ JVM implementation
ค่าคงที่ Priority
Thread.MIN_PRIORITY= 1Thread.NORM_PRIORITY= 5 (default)Thread.MAX_PRIORITY= 10
เมธอดหลัก
getPriority()- อ่านค่า prioritysetPriority(int newPriority)- เปลี่ยนค่า (โยนIllegalArgumentExceptionถ้านอกช่วง 1-10)
ตัวอย่าง
public class Demo extends Thread {
public void run() {
System.out.println("Now, inside the run method");
}
public static void main(String[] args) {
Demo t1 = new Demo();
Demo t2 = new Demo();
System.out.println("t1 priority: " + t1.getPriority()); // 5
System.out.println("t2 priority: " + t2.getPriority()); // 5
t1.setPriority(5);
t2.setPriority(3);
System.out.println("t1 new priority: " + t1.getPriority()); // 5
System.out.println("t2 new priority: " + t2.getPriority()); // 3
Thread mainThread = Thread.currentThread();
System.out.println("Main thread: " + mainThread.getName() + ", priority: " + mainThread.getPriority());
mainThread.setPriority(10);
System.out.println("Main thread new priority: " + mainThread.getPriority()); // 10
}
}
ผลลัพธ์
t1 priority: 5 t2 priority: 5 t1 new priority: 5 t2 new priority: 3 Main thread: main, priority: 5 Main thread new priority: 10
ข้อควรระวัง
- Priority เป็นเพียง hint ให้ scheduler ไม่ใช่คำสั่งบังคับ
- Starvation: thread priority ต่ำอาจไม่ได้รันเลยถ้า thread สูง佔 CPU
- ควรใช้
NORM_PRIORITYส่วนใหญ่ ปรับเฉพาะกรณีจำเป็น (เช่น background task ให้ต่ำ) - การตั้งค่า priority ไม่ควรเป็นกลไกหลักในการ sync thread - ใช้ synchronization primitives แทน