Wednesday, 10 June 2015

Write a class whose objects holds a current value and have a method to add that value, printing the new value


Code for Write a class whose objects holds a current value and have a method to add that value, printing the new value in Java



 



 



 
class Arr
{
   int int_array[]=newint[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();
    }

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

class ThreadArrAdd
{
    publicstaticvoid 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..

*/

No comments:

Post a Comment