কম্পিউটার

জাভাতে wait(), notify() এবং notifyAll() পদ্ধতির গুরুত্ব?


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

wait() পদ্ধতি সিনট্যাক্স

public final void wait() throws InterruptedException

বিজ্ঞপ্তি() পদ্ধতি সিনট্যাক্স

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(); //waiting, not running
         }
         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. জাভাতে ঘুম() এবং অপেক্ষা() পদ্ধতির মধ্যে পার্থক্য

  3. জাভা কনকারেন্সি - yield() পদ্ধতি

  4. জাভা 9 এ DestroForcibly() পদ্ধতির গুরুত্ব?