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

জাভাতে wait(), notify() এবং notifyAll() মেথডের গুরুত্ব


থ্রেডগুলো wait(), notify() এবং notifyAll() মেথডের মাধ্যমে একে অপরের সাথে যোগাযোগ করতে পারে। এই মেথডগুলো Object ক্লাসে সংজ্ঞায়িত ফাইনাল মেথড এবং শুধু সিঙ্ক্রোনাইজড কনটেক্সট থেকে কল করা যায়। wait() মেথড বর্তমান থ্রেডকে অপেক্ষা করতে বাধ্য করে যতক্ষণ না অন্য কোনো থ্রেড সেই অবজেক্টের জন্য notify() বা notifyAll() মেথড আহ্বান করে। notify() মেথড একটি একক থ্রেডকে জাগিয়ে দেয় যা সেই অবজেক্টের মনিটরে অপেক্ষা করছে। notifyAll() মেথড সকল থ্রেডকে জাগিয়ে দেয় যা সেই অবজেক্টের মনিটরে অপেক্ষা করছে। একটি থ্রেড wait() মেথড কল করে একটি অবজেক্টের মনিটরে অপেক্ষা করে। বর্তমান থ্রেড যদি অবজেক্টের মনিটরের মালিক না হয়, তবে এই মেথডগুলো IllegalMonitorStateException নিক্ষেপ করতে পারে।

wait() মেথড সিনট্যাক্স

public final void wait() throws InterruptedException

notify() মেথড সিনট্যাক্স

public final void notify()

notifyAll() মেথড সিনট্যাক্স

public final void notifyAll() 

উদাহরণ

public class WaitNotifyTest { 
    private static final long SLEEP_INTERVAL = 3000; 
    private boolean running = true; 
    private Thread thread; 
    
    public void start() { 
        print("Inside start() method"); 
        thread = new Thread(new Runnable() { 
            @Override 
            public void run() { 
                print("Inside run() method"); 
                try { 
                    Thread.sleep(SLEEP_INTERVAL); 
                } catch(InterruptedException e) { 
                    Thread.currentThread().interrupt(); 
                } 
                synchronized(WaitNotifyTest.this) { 
                    running = false; 
                    WaitNotifyTest.this.notify(); 
                } 
            } 
        }); 
        thread.start(); 
    } 
    
    public void join() throws InterruptedException { 
        print("Inside join() method"); 
        synchronized(this) { 
            while(running) { 
                print("Waiting for the peer thread to finish."); 
                wait(); // অপেক্ষা করছে, চলছে না 
            } 
            print("Peer thread finished."); 
        } 
    } 
    
    private void print(String s) { 
        System.out.println(s); 
    } 
    
    public static void main(String[] args) throws InterruptedException { 
        WaitNotifyTest test = new WaitNotifyTest(); 
        test.start(); 
        test.join(); 
    } 
}

আউটপুট

Inside start() method Inside join() method Waiting for the peer thread to finish. Inside run() method Peer thread finished.

  1. জাভা মেথড ব্যবহার করার পদ্ধতি

  2. জাভাতে sleep() এবং wait() মেথডের পার্থক্য

  3. জাভা কনকারেন্সি - yield() মেথড

  4. জাভা ৯-এ destroyForcibly() মেথডের গুরুত্ব