While learning Java Multithreading, I explored how thread priority actually works inside the JVM and how thread priorities influence scheduling. Let me breakdown. I. Thread Priority in Java Every thread in Java has a priority that helps the thread scheduler decide which thread should run first. Priority values range from 1 to 10. Java provides three commonly used constants: • Thread.MIN_PRIORITY → 1 • Thread.NORM_PRIORITY → 5 (default) • Thread.MAX_PRIORITY → 10 If we don’t explicitly set a priority, the thread gets the default priority (5). II. Getting and Setting Priority Java provides two methods: Thread.currentThread().getPriority(); Thread.currentThread().setPriority(int priority); Example: class Test { public static void main(String[] args) { System.out.println(Thread.currentThread().getPriority()); Thread.currentThread().setPriority(7); System.out.println(Thread.currentThread().getPriority()); } } Output: 5 7 III. Invalid Priority Values Thread priority must be between 1 and 10. If we try something like: Thread.currentThread().setPriority(15); The JVM throws a runtime exception: IllegalArgumentException IV. Priority Inheritance When a new thread is created, it inherits the priority of the parent thread. Example: If the main thread priority = 7 Then the child thread created by it will also start with priority = 7 unless we change it. V. Important Even if a thread has higher priority, execution is not guaranteed. Why? Because thread scheduling also depends on the operating system and JVM implementation. Some platforms may not strictly follow thread priority rules. Multithreading is not just about creating threads. #Day6 #Java #Multithreading #BackendDevelopment #Concurrency #SoftwareEngineering
Devi Sireesha S. Concurrency becomes much more manageable with executor frameworks. ThreadPoolExecutor provides control over core threads, maximum threads, and task queues, which is crucial for handling high workloads efficiently. I shared a detailed task execution explanation here: 🔗 https://www.garudax.id/posts/shivani-m-6bbb5621b_threadpool-task-execution-activity-7437395667272065025--joO
Great insights!!