Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6694743
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T06:08:14+00:00 2026-05-26T06:08:14+00:00

I have the following situation: In order to run a algorithm, i must run

  • 0

I have the following situation:

In order to run a algorithm, i must run several threads and each thread will set a instance variable x, right before it dies. The problem is that these threads dont return immediately:

public Foo myAlgorithm()
{
    //create n Runnables (n is big)
    //start these runnables (may take long time do die)

    //i need the x value of each runnable here, but they havent finished yet!

    //get average x from all the runnables

    return new Foo(averageX);
}

Should i use wait notify ? Or should i just embed a while loop and check for termination ?

Thanks everyone!

  • 1 1 Answer
  • 3 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T06:08:15+00:00Added an answer on May 26, 2026 at 6:08 am

    Create some shared storage to hold the x value from each thread, or just store the sum if that’s sufficient. Use a CountDownLatch to wait for the threads to terminate. Each thread, when finished, would call CountDownLatch.countDown() and your myAlgorithm method would use the CountDownLatch.await() method to wait for them.

    Edit: Here’s a complete example of the approach I suggested. It created 39 worker threads, each of which adds a random number to a shared sum. When all of the workers are finished, the average is computed and printed.

    import java.util.Random;
    import java.util.concurrent.CountDownLatch;
    import java.util.concurrent.atomic.AtomicInteger;
    
    class Worker implements Runnable {
    
        private final AtomicInteger sum;
        private final CountDownLatch latch;
    
        public Worker(AtomicInteger sum, CountDownLatch latch) {
            this.sum = sum;
            this.latch = latch;
        }
    
        @Override
        public void run() {
            Random random = new Random();
    
            try {
                // Sleep a random length of time from 5-10s
                Thread.sleep(random.nextInt(5000) + 5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            // Compute x
            int x = random.nextInt(500);
    
            // Add to the shared sum
            System.out.println("Adding " + x + " to sum");
            sum.addAndGet(x);
    
            // This runnable is finished, so count down
            latch.countDown();
        }
    }
    
    class Program {
    
        public static void main(String[] args) {
            // There will be 39 workers
            final int N = 39;
    
            // Holds the sum of all results from all workers
            AtomicInteger sum = new AtomicInteger();
            // Tracks how many workers are still working
            CountDownLatch latch = new CountDownLatch(N);
    
            System.out.println("Starting " + N + " workers");
    
            for (int i = 0; i < N; i++) {
                // Each worker uses the shared atomic sum and countdown latch.
                Worker worker = new Worker(sum, latch);
    
                // Start the worker
                new Thread(worker).start();
            }
    
            try {
                // Important: waits for all workers to finish.
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
    
            // Compute the average
            double average = (double) sum.get() / (double) N;
    
            System.out.println("    Sum: " + sum.get());
            System.out.println("Workers: " + N);
            System.out.println("Average: " + average);
        }
    
    }
    

    The output should be something like this:

    Starting 39 workers
    Adding 94 to sum
    Adding 86 to sum
    Adding 454 to sum
    ...
    ...
    ...
    Adding 358 to sum
    Adding 134 to sum
    Adding 482 to sum
        Sum: 10133
    Workers: 39
    Average: 259.8205128205128
    

    Edit: Just for fun, here is an example using ExecutorService, Callable, and Future.

    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.List;
    import java.util.Random;
    import java.util.concurrent.Callable;
    import java.util.concurrent.ExecutionException;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Future;
    import java.util.concurrent.ScheduledThreadPoolExecutor;
    
    class Worker implements Callable<Integer> {
    
        @Override
        public Integer call() throws Exception {
            Random random = new Random();
    
            // Sleep a random length of time, from 5-10s
            Thread.sleep(random.nextInt(5000) + 5000);
    
            // Compute x
            int x = random.nextInt(500);
            System.out.println("Computed " + x);
    
            return x;
        }
    
    }
    
    public class Program {
    
        public static void main(String[] args) {
            // Thread pool size
            final int POOL_SIZE = 10;
    
            // There will be 39 workers
            final int N = 39;
    
            System.out.println("Starting " + N + " workers");
    
            // Create the workers
            Collection<Callable<Integer>> workers = new ArrayList<Callable<Integer>>(N);
    
            for (int i = 0; i < N; i++) {
                workers.add(new Worker());
            }
    
            // Create the executor service
            ExecutorService executor = new ScheduledThreadPoolExecutor(POOL_SIZE);
    
            // Execute all the workers, wait for the results
            List<Future<Integer>> results = null;
    
            try {
                // Executes all tasks and waits for them to finish
                results = executor.invokeAll(workers);
            } catch (InterruptedException e) {
                e.printStackTrace();
                return;
            }
    
            // Compute the sum from the results
            int sum = 0;
    
            for (Future<Integer> future : results) {
                try {
                    sum += future.get();
                } catch (InterruptedException e) {
                    e.printStackTrace(); return;
                } catch (ExecutionException e) {
                    e.printStackTrace(); return;
                }
            }
    
            // Compute the average
            double average = (double) sum / (double) N;
    
            System.out.println("         Sum: " + sum);
            System.out.println("     Workers: " + N);
            System.out.println("     Average: " + average);
        }
    
    }
    

    The output should look like this:

    Starting 39 workers
    Computed 419
    Computed 36
    Computed 338
    ...
    ...
    ...
    Computed 261
    Computed 354
    Computed 112
             Sum: 9526
         Workers: 39
         Average: 244.25641025641025
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have following situation: class TextBoxCellControl : TextBox, IDataGridViewCellControl class EnhancedTextBoxCellControl : Panel, IDataGridViewCell
I have following situation: I have loged user, standard authentication with DB table $authAdapter
I have following situation. A main table and many other tables linked together with
I have following situation. In a constructor of a pseudo class I attach a
I have following situation (simplified, of course): MyDomain.groovy: class MyDomain { MyAnotherDomain anotherDomain //
I have following situation, String a=<em>crawler</em> <em> Yeahhhhh </em></a></h3><table; System.out.println(a.indexOf(</em>)); It returns the 11
I have following situation: String a = A Web crawler is a computer program
I have following Situation, Server A sends some data (HTML form) to server B,
I have the following situation: I built an Access form with a subform (which
I have the following situation: class A { public: A(int whichFoo); int foo1(); int

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.