Logo 
Search:

Java Articles

Submit Article
Home » Articles » Java » Networking TechnologyRSS Feeds

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

Posted By: Emma Campbell     Category: Java     Views: 2007

Write a class whose objects holds a current value and have a method to add that value, printing the new value. Write a program that creates such an object, creates multiple threads, and invokes the adding method repeatedly from each thread. (Write a program such that no addition can be lost).

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..

*/
  
Share: 



Emma Campbell
Emma Campbell author of Write a class whose objects holds a current value and have a method to add that value, printing the new value is from Toronto, Canada.
 
View All Articles

Related Articles and Code:


 
Please enter your Comment

  • Comment should be atleast 30 Characters.
  • Please put code inside [Code] your code [/Code].

 
No Comment Found, Be the First to post comment!