• 06-29-2010, 06:53 AM
ferdzz
Hi all,

I am working on an exercise that tells me:

Assume that in the class that you are currently writing, there is already a method long calculate() that returns a long value produced by an algorithm that takes an unpredictable time to finish.
Write a method void sum(int n) that launches a total of n new threads, each of which calls this method calculate, and after all these threads have finished, your method sum returns the sum of values that were produced by these n calls.

I have written my code, I need is confirmation if the code is logically and syntactically correct. Thanks in advance.

Here are my instance fields
Code:

```        private volatile boolean running = true;         private static Object mutex;         private static ArrayList <Sums> sum = new ArrayList<Sums>();         private double total;```
And my sum method
Code:

```                public void sum(int n){                 for (int i = 0; i < n; i++){                         new Thread(new Runnable(){                                 public void run() {                                         try{                                                 while(running){                                                         synchronized(mutex){                                                                 this.wait();                                                                 for (Sums e: sum){                                                                         calculate();                                                                         total += e;                                                                 }                                                                        }                                                 }                                         }catch (InterruptedException e){}                                 }                         }).start();                 } System.out.print(total);         }```
There is also one syntax error, on the line "total += e;" and there were no suggestions on Eclipse on how to fix it. Any help is greatly appreciated.
• 06-29-2010, 08:40 AM
JosAH
Quote:

Originally Posted by ferdzz
There is also one syntax error, on the line "total += e;" and there were no suggestions on Eclipse on how to fix it. Any help is greatly appreciated.

Variable 'e' has type Sums; you can only use the'+' operator on primitive numeric types (ints, doubles etc) and Strings (the latter is a little compiler trick).

kind regards,

Jos
• 06-29-2010, 01:19 PM
Norm
Add a method to the Sums class to return its value as double.