0

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();
    }
Yoav Linder
  • 123
  • 1
  • 10
  • Java is pass by value. Assigning a new value to an argument won't modify the original variable. – JB Nizet Jan 14 '18 at 11:36
  • @JBNizet this in an exrecise for my lesson in school... im not understanding threads so good (especially synchronized) i dont really understand how i can add to a variable in my main (sum) the number that generated in the thread – Yoav Linder Jan 14 '18 at 11:41
  • 1
    This has nothing to do with threads. If you have a method `void increment(a) { a++; }`, and call it `increment(i)`, then the value of `i` won't change. Because Java is pass by value. A copy of i is passed to increment(). – JB Nizet Jan 14 '18 at 11:46
  • See: https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value – AlexC Jan 14 '18 at 12:36

1 Answers1

0

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
garywzh
  • 481
  • 3
  • 7