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();
    }

1 answer

  • answered 2018-01-14 12:10 garywzh

    Try this

    public class Summing implements Runnable {
    
        int a;
    
        public Summing(int a) {
            this.a = a;
        }
    
        public void run() {
            addRondom();
        }
    
        public void addRondom() {
            Random rand = new Random();
            int n = rand.nextInt(10) + 1;
            System.out.println("number generated: " + n);
            synchronized (this) {
                a += n;
            }
        }
    }
    

    and then

    public static void main(String[] args) {
        int base = 0;
    
        Summing sum2 = new Summing(base);
    
        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();
    
        try {
            t1.join();
            t2.join();
            t3.join();
            t4.join();
            t5.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    
        System.out.print("final result: " + sum2.a);
    }
    

    It works well

    number generated: 1
    number generated: 3
    number generated: 7
    number generated: 4
    number generated: 5
    final result: 20
    Process finished with exit code 0