مشخصات مقاله
آموزش Java – اولویت اجرا و priority آبجکت های thread در Java
آموزش Java – اولویت اجرا و priority آبجکت های thread در Java
تمامی thread ها دارای یک اولویت اجرا و priority هستند. مقدار priority با یک عدد صحیح بین 1 تا 10 نمایش داده می شود (5 اولویت پیش فرض thread ها می باشد و مقدار 10 نشانگر بالاترین میزان اولویت اجرا می باشد). thread scheduler اغلب thread ها را بر اساس مقدار priority آن ها (که مبتنی بر الگوریتم preemptive هست) اجرا می نماید. اما با قطعیت نمی توان گفت که کدام thread اول اجرا می شود و این تا حدی بستگی به مشخصات JVM دارد.
ثوابت موجود در کلاس Thread
1 2 3 4 | public static int MIN_PRIORITY public static int NORM_PRIORITY public static int MAX_PRIORITY <button></button> |
مقدار اولویت یک thread به صورت پیش فرض برابر 5 (NORM_PRIORITY) می باشد. پایین ترین میزان اولویت اجرای thread برابر 1 بوده که در ثابت MIN_PRIORITY ذخیره شده و بالاترین میزان اولویت اجرا 10 می باشد که در ثابت MAX_PRIORITY قرار دارد.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class TestMultiPriority1 extends Thread{ public void run(){ System.out.println( "running thread name is:" +Thread.currentThread().getName()); System.out.println( "running thread priority is:" +Thread.currentThread().getPriority()); } public static void main(String args[]){ TestMultiPriority1 m1= new TestMultiPriority1(); TestMultiPriority1 m2= new TestMultiPriority1(); m1.setPriority(Thread.MIN_PRIORITY); m2.setPriority(Thread.MAX_PRIORITY); m1.start(); m2.start(); } } <button></button> |
خروجی:
1 2 3 4 5 | running thread name is:Thread-0 running thread priority is:10 running thread name is:Thread-1 running thread priority is:1 <button></button> |