Results 1 to 20 of 20
 06182010, 12:54 PM #1Member
 Join Date
 Jun 2010
 Posts
 12
 Rep Power
 0
Using threads to calculate the average
Hi all, I want to find the average of n numbers using three threads. This is the code that I have tried for. But I don't know to continue on it. Please help.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.io.*;
class MyRunnable implements Runnable {
private final long countUntil;
MyRunnable(long countUntil) {
this.countUntil = countUntil;
}
@Override
public void run() {
long sum = 0;
long average =0;
for (long i = 1; i < countUntil; i++) {
sum += i;
average = sum/i;
}
System.out.println(average);
}
}
public class Main1 {
private static final int NTHREDS = 3;
public static void main(String[] args) {
System.out.println("Enter a number");
String line = null;
int val = 0;
try {
BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
line = is.readLine();
val = Integer.parseInt(line);
} catch (NumberFormatException ex) {
System.err.println("Not a valid number: " + line);
} catch (IOException e) {
System.err.println("Unexpected IO ERROR: " + e);
}
ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
for (int i = 0; i < 3; i++) {
Runnable worker = new MyRunnable(10L+i);
executor.execute(worker);
}
// This will make the executor accept no new threads
// and finish all existing threads in the queue
executor.shutdown();
// Wait until all threads are finish
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
}
 06182010, 01:15 PM #2I want to find the average of n numbers using three threads
Can you explain your design? What does each thread do?
 06182010, 01:39 PM #3Member
 Join Date
 Jun 2010
 Posts
 12
 Rep Power
 0
Hi.. This is an assignment given for Concurrent Programming. My design is when the user input the numbers add them in to a list and devide the list in to three and assign each thread to calculate the sum and finally average.
ThanksLast edited by gish; 06182010 at 01:41 PM.
 06182010, 01:42 PM #4
Please use the [ code] tags on your code to preserve the formatting. Unformatted code is hard to read.
The code you posted does not compile without errors.Last edited by Norm; 06182010 at 01:45 PM.
 06182010, 01:46 PM #5Member
 Join Date
 Jun 2010
 Posts
 12
 Rep Power
 0
ok...sorry for tht... can u tell me how to devide that number in to 3segments and assign each thread?
 06182010, 01:51 PM #6how to divide that number in to 3 segments
Pass starting position and number of items to be processed to the working method.
For example For a list of 9 items: 0 for 3(items 0,1,2), 3 for 3(3,4,5) and 6 for 3(6,7,8)
If the length of list not divisible by 3, give one thread the remaining
 06182010, 02:19 PM #7
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 14,288
 Blog Entries
 7
 Rep Power
 24
Be careful with that; you have to keep track of the total number of numbers you have fed to each thread. Better pad the sequence of numbers with zeros so each thread can calculate its own average and the controlling thread just has to sum those averages and divide the sum by three.
kind regards,
Jos (< micro optimizer ;)
 06182010, 05:18 PM #8Member
 Join Date
 Jun 2010
 Posts
 12
 Rep Power
 0
Thanks for the replies. Can you give me a code example for passing the devided list in to threads?
Last edited by gish; 06182010 at 06:03 PM.
 06182010, 06:16 PM #9Better pad the sequence of numbers with zeros
object.method(array, start, count); // call the method
public int method(int[] ar, int start, int count) { ...} // define the method
 06182010, 07:10 PM #10Member
 Join Date
 Jun 2010
 Posts
 12
 Rep Power
 0
Hi.. Thanks for the reply Norm. This is what I did.
int count = numbers.size();
int pointer = count/3;
int remainder = count%3;
for (int i = 0; i < 3; i++){
// adding the values in segment 1
if (i == 0){
Thread mc1 = new MeanCalcThread(numbers,0,pointer);
mc1.start();
}
else if (i==1){
Thread mc2 = new MeanCalcThread(numbers,pointer,pointer);
mc2.start();
}
else
Thread mc3 = new MeanCalcThread(numbers,(pointer*2),(pointer+remain der));
mc3.start();
}
Here I'm getting an error at Thread mc3 as "Thread can't be resolved". Could you please tell me why?
 06182010, 07:16 PM #11I'm getting an error
Also please use code tags to keep code formatting.
 06182010, 08:05 PM #12Member
 Join Date
 Jun 2010
 Posts
 12
 Rep Power
 0
Hi..sorry for the same mistake. I have found the error, just missing a bracket. Thanks for the help.
 06182010, 08:08 PM #13Better pad the sequence of numbers with zeros so each thread can calculate its own average and the controlling thread just has to sum those averages and divide the sum by three.
For example, take a list of numbers all the same value. Any subpart's average will be the number. If there are n subparts, each will have the same average. Add together the n subparts averages and divide by n and you get the number. With padding the average of that subpart will be different than the number.
 06182010, 09:23 PM #14
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 14,288
 Blog Entries
 7
 Rep Power
 24
 06182010, 11:10 PM #15
Is there a way to partition a set into unequal groups and and get the correct answer?
Put some math on this.
 06192010, 05:23 AM #16Member
 Join Date
 Jun 2010
 Posts
 12
 Rep Power
 0
I am still confused about the way to do this in threads. should we have to put that method as run method? If else what we have to put in the run method of each thread?
Thnanks.
 06192010, 12:26 PM #17
@JosAH
But now take a bunch of unequal numbers and not a multiple of three numbers in total
To merge the averages returned by the n threads, sum up the average from each thread times the number of items it had, add these to the total and divide by the total items in the list: Avg = (avg_p1*nbr_p1 + avg+p2*nbr_p2 + ... avg_pn*nbr_pn) / total nbr
@OP back to the problem
Create a class for each Averager class, have the class extend Runnable (has run method), save references to class objects,
pass the array of number, starting index and count to constructor and start a Thread with the class. The class should have a get method to return the results.
Next problem I'll have to research is how the controlling thread waits for all the worker threads to finish before doing the final total. There are some classes that do this for you.
 06192010, 01:08 PM #18Member
 Join Date
 Jun 2010
 Posts
 12
 Rep Power
 0
hi,thanks for the reply..
 06192010, 02:42 PM #19
 Join Date
 Sep 2008
 Location
 Voorschoten, the Netherlands
 Posts
 14,288
 Blog Entries
 7
 Rep Power
 24
 06192010, 02:57 PM #20
Similar Threads

Calculating average
By clocksaysits9 in forum New To JavaReplies: 4Last Post: 04062010, 05:03 AM 
Need help in calculating average value on this format ....
By motress in forum New To JavaReplies: 1Last Post: 03112010, 05:21 AM 
calculate average letter grades...
By Christ90 in forum New To JavaReplies: 14Last Post: 01252010, 01:59 AM 
Calculate Average
By sthack99 in forum New To JavaReplies: 4Last Post: 06132008, 11:09 AM 
Calculate average age for women and men?
By Legoland in forum New To JavaReplies: 3Last Post: 04182007, 10:38 AM
Bookmarks