কম্পিউটার টিউটোরিয়াল

জাভা মাল্টিথ্রেডিং-এ থ্রেড প্রায়োরিটি (Thread Priority)


মাল্টিথ্রেডিং (multi-threading) পরিস্থিতিতে, একটি থ্রেড স্কিডিউলার (thread scheduler) থ্রেডগুলোর প্রায়োরিটি (priority) ভিত্তিতে স্পেসিফিক প্রসেসে অ্যাসাইন করে। একটি জাভা থ্রেড একটি প্রি-অ্যাসাইনড (pre-assigned) প্রায়োরিটি দিয়ে আসে। এর বাওয়जूद, জাভা ভার্চুয়াল মেশিন (JVM) থ্রেডগুলোর প্রায়োরিটি অ্যাসাইন করতে পারে বা প্রোগ্রামাররা এক্সপ্লিসিটলি দিতে পারে। থ্রেড প্রায়োরিটির মানরেঞ্জ ১ থেকে ১০ (ইনক্লুসিভ)। প্রায়োরিটির সাথে জড়িত তিনটি স্ট্যাটিক ভেরিয়েবল:

  • MAX_PRIORITY - একটি থ্রেডের সর্বোচ্চ প্রায়োরিটি, ডিফল্ট মান ১০।
  • NORM_PRIORITY - একটি থ্রেডের ডিফল্ট প্রায়োরিটি, ডিফল্ট মান ৫।
  • MIN_PRIORITY - একটি থ্রেডের ন্যূনতম প্রায়োরিটি, ডিফল্ট মান ১।

জাভায় 'getPriority()' মেথড থ্রেডের সাথে বাউন্ড প্রায়োরিটি মান রিটার্ন করতে সাহায্য করে।

'setPriority()' মেথড একটি দिये गये থ্রেডের প্রায়োরিটি মান পরিবর্তন করে। এটি IllegalArgumentException থ্রো করে যদি থ্রেড প্রায়োরিটি ১-এর চেয়ে কম বা ১০-এর চেয়ে বেশি হয়।

উদাহরণ

import java.lang.*; 
public class Demo extends Thread{ 
    public void run(){ 
        System.out.println("Now, inside the run method"); 
    } 
    public static void main(String[]args){ 
        Demo my_thr_1 = new Demo(); 
        Demo my_thr_2 = new Demo(); 
        System.out.println("The thread priority of first thread is : " + my_thr_1.getPriority()); 
        System.out.println("The thread priority of second thread is : " + my_thr_2.getPriority()); 
        my_thr_1.setPriority(5); 
        my_thr_2.setPriority(3); 
        System.out.println("The thread priority of first thread is : " + my_thr_1.getPriority()); 
        System.out.println("The thread priority of second thread is : " + my_thr_2.getPriority()); 
        System.out.print(Thread.currentThread().getName()); 
        System.out.println("The thread priority of main thread is : " + Thread.currentThread().getPriority()); 
        Thread.currentThread().setPriority(10); 
        System.out.println("The thread priority of main thread is : " + Thread.currentThread().getPriority()); 
    } 
}

আউটপুট

The thread priority of first thread is : 5
The thread priority of second thread is : 5
The thread priority of first thread is : 5
The thread priority of second thread is : 3
The thread priority of main thread is : 5
The thread priority of main thread is : 10

Demo নামে একটি ক্লাস Thread বেস ক্লাস থেকে ইনহেরিট করে। 'run' ফাংশন ডিফাইন করা হয়েছে এবং একটি প্রাসঙ্গিক মেসেজ দেওয়া হয়েছে। main ফাংশনে Demo ক্লাসের দুটি ইনস্ট্যান্স তৈরি করা হয় এবং তাদের প্রায়োরিটি 'getPriority' ফাংশন কল করে বের করা হয়। সেগুলো কনসোলে প্রিন্ট করা হয়। এরপর, Demo ইনস্ট্যান্সগুলোর প্রায়োরিটি 'setPriority' ফাংশন ব্যবহার করে অ্যাসাইন করা হয়। আউটপুট কনসোলে প্রদর্শিত হয়। থ্রেডের নামগুলো 'getName' ফাংশন ব্যবহার করে স্ক্রিনে প্রিন্ট করা হয়।

  1. জাভাতে একটি চলমান থ্রেড ইন্টারাপ্ট করুন

  2. জাভাতে থ্রেড প্রায়োরিটির গুরুত্ব

  3. জাভাতে থ্রেড স্টপ করুন

  4. জাভাতে ইউজার থ্রেড এবং ডেমন থ্রেডের পার্থক্য