Results 1 to 20 of 20
  1. #1
    gish is offline Member
    Join Date
    Jun 2010
    Posts
    12
    Rep Power
    0

    Default 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");
    }
    }

  2. #2
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    I want to find the average of n numbers using three threads
    Why do you need 3 threads to do this?
    Can you explain your design? What does each thread do?

  3. #3
    gish is offline Member
    Join Date
    Jun 2010
    Posts
    12
    Rep Power
    0

    Default

    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.



    Thanks
    Last edited by gish; 06-18-2010 at 01:41 PM.

  4. #4
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    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; 06-18-2010 at 01:45 PM.

  5. #5
    gish is offline Member
    Join Date
    Jun 2010
    Posts
    12
    Rep Power
    0

    Default

    ok...sorry for tht... can u tell me how to devide that number in to 3segments and assign each thread?

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    how to divide that number in to 3 segments
    Take total length of list and divide by 3
    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

  7. #7
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,655
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Norm View Post
    If the length of list not divisible by 3, give one thread the remaining
    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 ;-)

  8. #8
    gish is offline Member
    Join Date
    Jun 2010
    Posts
    12
    Rep Power
    0

    Default

    Thanks for the replies. Can you give me a code example for passing the devided list in to threads?
    Last edited by gish; 06-18-2010 at 06:03 PM.

  9. #9
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    Better pad the sequence of numbers with zeros
    Or pass the divisor(total count) as arg to the method.

    object.method(array, start, count); // call the method

    public int method(int[] ar, int start, int count) { ...} // define the method

  10. #10
    gish is offline Member
    Join Date
    Jun 2010
    Posts
    12
    Rep Power
    0

    Default

    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?

  11. #11
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    I'm getting an error
    Please copy and post the full text of the error message here.

    Also please use code tags to keep code formatting.

  12. #12
    gish is offline Member
    Join Date
    Jun 2010
    Posts
    12
    Rep Power
    0

    Default

    Hi..sorry for the same mistake. I have found the error, just missing a bracket. Thanks for the help.

  13. #13
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    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.
    I think we've been asleep on this bit.
    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.

  14. #14
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,655
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Norm View Post
    I think we've been asleep on this bit.
    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.
    But now take a bunch of unequal numbers and not a multiple of three numbers in total ...

    kind regards,

    Jos

    ps. agreed, I've been sleeping too but it was Friday afternoon ;-)
    Last edited by JosAH; 06-18-2010 at 09:27 PM.

  15. #15
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    Is there a way to partition a set into unequal groups and and get the correct answer?
    Put some math on this.

  16. #16
    gish is offline Member
    Join Date
    Jun 2010
    Posts
    12
    Rep Power
    0

    Default

    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.

  17. #17
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    @JosAH
    But now take a bunch of unequal numbers and not a multiple of three numbers in total
    We shouldn't hijack this thread, but I just had to say:
    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.

  18. #18
    gish is offline Member
    Join Date
    Jun 2010
    Posts
    12
    Rep Power
    0

    Default

    hi,thanks for the reply..

  19. #19
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,655
    Blog Entries
    7
    Rep Power
    21

    Default

    Quote Originally Posted by Norm View Post
    @JosAH

    We shouldn't hijack this thread, but I just had to say:
    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
    <hijacking a bit further>
    But then there is no need for the threads to divide their total by their number of numbers and the 'main' thread could simply add those three totals and divide by nbr
    </hijacking a bit further>

    kind regards,

    Jos

  20. #20
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,562
    Rep Power
    25

    Default

    <hijacking a bit further>
    OK. That redefines the function of the threads: They sum their list vs computing its average.
    </hijacking a bit further>

Similar Threads

  1. Calculating average
    By clocksaysits9 in forum New To Java
    Replies: 4
    Last Post: 04-06-2010, 05:03 AM
  2. Replies: 1
    Last Post: 03-11-2010, 04:21 AM
  3. calculate average letter grades...
    By Christ90 in forum New To Java
    Replies: 14
    Last Post: 01-25-2010, 12:59 AM
  4. Calculate Average
    By sthack99 in forum New To Java
    Replies: 4
    Last Post: 06-13-2008, 11:09 AM
  5. Calculate average age for women and men?
    By Legoland in forum New To Java
    Replies: 3
    Last Post: 04-18-2007, 10:38 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •