Java-Inter Thread Communication (Another Example)

Program



Program Source

class Data {
   
    boolean condition = false;
    
    synchronized void print_1_to_5()
    {
        condition = true;
        try{
            for(int i=1;i<=5;i++)
            {
                Thread.sleep(1000);
                System.out.println("Print_1_to_5 : "+i);
            }
        }catch(InterruptedException ie)
        {
            System.out.println("Child Thread Interrupted");
        }
        notify();
    }
    
    synchronized void print_6_to_10()
    {
        if(!condition)
        {
            try{
                System.out.println("First thread called Print_6_to_10 method");
                System.out.println("So its waiting to second thread complete");
                wait();
                System.out.println("Second thread complete the execution and sent the notification");
                System.out.println("So first thread resumed");
            }catch(InterruptedException ie)
            {
                System.out.println("Child Thread Interrupted");
            }
        }    
        try{
            for(int i=6;i<=10;i++)
            {
                Thread.sleep(1000);
                System.out.println("Print_6_to_10 : "+i);
            }
        }catch(InterruptedException ie)
        {
            System.out.println("Child Thread Interrupted");
        }  
    }
}

class PrintOneToFive extends Thread {
    
    Data da;
    
    PrintOneToFive(Data da)
    {
        this.da = da;
        start();
    }
    
    public void run()
    {
        da.print_1_to_5();
    }
}

class PrintSixToTen extends Thread {
    
    Data da;
    
    PrintSixToTen(Data da)
    {
        this.da = da;
        start();
    }
    
    public void run()
    {
        da.print_6_to_10();
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        Data da = new Data();
        PrintSixToTen th1 = new PrintSixToTen(da);
        PrintOneToFive th2 = new PrintOneToFive(da);
    }
}

Leave a Comment