dimanche 14 janvier 2018

I want to generate 5 random numbers using 5 Threads(each thread generates 1 number) and then to sum up the numbers and print the sum of them

this is my class that generates the numbers and adding the numbers im getting a random number and adding returning it in the "summing" function

public class summing implements Runnable
{ 
int a;
public summing(int a){
    this.a = a;
}

public void run()
{
    add(a);
}

public void add(int a)
{
    Random rand = new Random();
    int  n = rand.nextInt(10) + 1;
    System.out.println("nmber generated:" + n); 
    synchronized (this)
    {
        a += n;   
    }
}

and this is my main class i am making 5 threads and i want to add here the random numbers to the sum variable but it does not working.

public static void main(String[] args)
{
    int sum = 0;
    summing sum2 = new summing(sum);
    Thread t1 = new Thread(sum2);
    Thread t2 = new Thread(sum2);
    Thread t3 = new Thread(sum2);
    Thread t4 = new Thread(sum2);
    Thread t5 = new Thread(sum2);
    t1.start();
    t2.start();
    t3.start();
    t4.start();
    t5.start();
    }




Aucun commentaire:

Enregistrer un commentaire