ในแอปพลิเคชัน Multi-threaded แต่ละ thread มี Priority (ลำดับความสำคัญ) Thread Scheduler มอบ CPU ให้ thread ตาม priority สูงสุดก่อน ค่าเริ่มต้น = 5 (NORM_PRIORITY) ดูค่าได้ด้วย getPriority()
ค่าคงที่ Priority ในคลาส Thread
- MAX_PRIORITY = 10 - สูงสุด
- NORM_PRIORITY = 5 - ปกติ (Default)
- MIN_PRIORITY = 1 - ต่ำสุด
ไวยากรณ์
public final int getPriority()
ตัวอย่าง: ตั้งค่าและอ่าน Thread Priority
public class ThreadPriorityTest extends Thread {
public static void main(String[] args) {
ThreadPriorityTest t1 = new ThreadPriorityTest();
ThreadPriorityTest t2 = new ThreadPriorityTest();
ThreadPriorityTest t3 = new ThreadPriorityTest();
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
}
}
ผลลัพธ์
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
หมายเหตุ: Priority เป็นเพียงคำแนะนำให้ Scheduler ไม่รับประกันลำดับการรันจริง ขึ้นอยู่กับ OS และ JVM Implementation