Java Program on Wait Notify in Multithreading

Free Java courses with 37 real-time projects - Learn Java

Program 1

package dataflair;

import java.util.ArrayList;

public class MyThread extends Thread
{
         int sum=0;
        public void run()
        {
            synchronized(this)
            {      
                System.out.println("This is MyThread Thread Starts");
             int i;
             for(i=1;i<=1000;i++)
              {
                sum=sum+i;
              }
             this.notify();
              System.out.println("This is MyThread After Notification");
           } 
        }
}

Program 2

package dataflair;

public class TestMain 
{
    public static void main(String[] args) throws InterruptedException
    {
           MyThread M=new MyThread();
           M.start();
           synchronized(M)
           {
                 System.out.println("This is Main Thread Starts");
                  M.wait();  /// Waiting
           }
           System.out.println("Notification recived");
            System.out.println(M.sum);
            System.out.println("This is Main Thread Ends");
    }
    
}

Your opinion matters
Please write your valuable feedback about DataFlair on Google

follow dataflair on YouTube

Leave a Reply

Your email address will not be published. Required fields are marked *