Java Blog

 
 
 
class Arr
{
   int int_array[]=new int[5];
   synchronized void add_to_array(int int_array[], int k)
   {
       for(int i=0; i<5; i++)
       {
           int_array[i]+=k;
           System.out.println(int_array[i]);
       }
   }
}

class Caller implements Runnable
{
    Arr A;
    int array[]={1, 2, 3, 4, 5};
    int val;
    Thread t;
    public Caller(Arr ar, int k)
    {
        A=ar;
        val=k;
        t=new Thread(this);
        t.start();
    }

    public void run()
    {
        System.out.println(\"Thread starts..\");
        A.add_to_array(array, val);
        System.out.println(\"Thread stops..\");
    }
}

class ThreadArrAdd
{
    public static void main(String args[])
    {
        Arr A1=new Arr();

        Caller ob1=new Caller(A1, 2);
        Caller ob2=new Caller(A1, 4);
        Caller ob3=new Caller(A1, 1);
        try
        {
            ob1.t.join();
            ob2.t.join();
            ob3.t.join();
        }
        catch(InterruptedException e)
        {
            System.out.println(\"Interrupted...\");
        }
    }
}

/* 
            OUTPUT

Thread starts..
3
4
5
6
7
Thread stops..
Thread starts..
5
6
7
8
9
Thread stops..
Thread starts..
2
3
4
5
6
Thread stops..

*/