Space for google add

Write a java program to calculate the sum and average of an array of 1000 integers (generated randomly) using 10 threads.

 


Write a java program to calculate the sum and average of an array of 1000 integers

(generated randomly) using 10 threads. Each thread calculates the sum of 100 integers.

Use these values to calculate the average. [Use join method ]


import java.util.*;

class Mythread extends Thread
{
    private int no[];
    private int b,e;
    private int sum;

    Mythread(int a[],int m,int n)
    {
        no=a;
        b=m;
        e=n;
        sum=0;
    }

    public void run()
    {
        for(int i=b;i<=e;i++)
        sum=sum+no[i];
    }

    public int getSum()
    {
        return sum;
    }
}

class Arraythread
{
        public static void main(String args[])
    {
        int a[]=new int[1000];
        int i=0,x=100;
        float tot=0.0f,avg;
       
        Random r=new Random();
        Mythread s[]=new Mythread[10];
        for(i=0;i<1000;i++)
        a[i]=r.nextInt(100);
       
        try
        {
            for(i=0;i<10;i++)
            {
                s[i]=new Mythread(a,x*i,(x*i)+99);
                s[i].start();
                s[i].join();
            }
        }  
        catch(InterruptedException ie)
        {
            System.out.println("Exception occured"+ie);
        }
        System.out.println("Randomly created Array");
        for(i=0;i<1000;i++)
        System.out.print("\t"+a[i]);
        for(i=0;i<10;i++)
        tot=tot+s[i].getSum();
        avg=tot/1000;
        System.out.println("Average is"+avg);
    }                      
}

Post a Comment

0 Comments