?
Solved

How to preform Multi Thread Join Async

Posted on 2010-08-24
9
Medium Priority
?
484 Views
Last Modified: 2013-12-29
Hi I have a program that is running a few threads.
now i want to be able to run these few threads, and then to wait for all of them to end.

In my code sample you can see the code i am attempting but if i look at what actully happens, the join loop waits for the first thread to end only then it goes through the rest of the threads and joins them... what i would basiclly want to do, is let all the threads run and have a point where i know they all finished without calling finish on all of them because what would happen in a 3 threads example is this:

first iteration on joins:
th1 : isalive = false
th2 : isalive = true
th3 : isalive = true

second iteration on joins:

th1 : isalive = false
th2 : isalive = false
th3 : isalive = true

etc...

so what im looking for is how to wait for all them 3 to end without causing a while loop of busy/waiting on these threads..
//start threads
	for (int i=0;i<arrForagers.size();i++)
	{
		arrForagers.get(i).start();
	}	


//create join action for all the threads ************this is the problem*****************
for (int i=0;i<arrForagers.size();i++)
		{
		try {
			arrForagers.get(i).join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		}	
//from this point all the threads have completed successfully.

Open in new window

0
Comment
Question by:Avir
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 2
9 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 33513249
0
 

Author Comment

by:Avir
ID: 33513419
i have tried using latch countdown but the problem is that when i start my thread the latch closes immidiatly afterwards because my code is running async (i call another thread to do the work for me).
see my code sample of what i did and still no go.

private static class Worker implements Runnable
    {
        CountDownLatch startLatch;
 
        CountDownLatch stopLatch;
 
        Forager f;
 
        Worker(CountDownLatch startLatch, CountDownLatch stopLatch, Forager f)
        {
            this.startLatch = startLatch;
            this.stopLatch = stopLatch;
            this.f = f;
        }
 
        public void run()
        {
            try
            {
                startLatch.await(); // wait until the latch has counted down to
                                    // zero
            } catch (InterruptedException ex)
            {
                ex.printStackTrace();
            }
            //this starts
            f.start();
            //Occurs immediately after not allowing this to complete!
            stopLatch.countDown();
        }
    }

//in the main:
CountDownLatch startSignal = new CountDownLatch(1);
        CountDownLatch stopSignal = new CountDownLatch(arrForagers.size());
        for (int i = 0; i < arrForagers.size(); i++)
        {
            new Thread(new Worker(startSignal, stopSignal, arrForagers.get(i)))
                    .start();
        }
        System.out.println("Go");
        startSignal.countDown();
        try
        {
            stopSignal.await();
        } catch (InterruptedException ex)
        {
            ex.printStackTrace();
        }

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 33516017
I'm wondering why you're using two latches?
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:Avir
ID: 33516040
this is what most code samples were showing.. however i am still not able to overcome this issue..
 
0
 
LVL 92

Expert Comment

by:objects
ID: 33516147
> what i would basiclly want to do, is let all the threads run and have a point where i know they all finished

which is what your existing code will do

> without calling finish on all of them because what would happen in a 3 threads example is this:

can you explain the problem further
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 33516165
>>this is what most code samples were showing.

Have a look at the api doc example
0
 

Author Comment

by:Avir
ID: 33516210
I have achieved this, but because this is done inside a loop what would actully be executed would be:
1. arrForagers.get(0).start();
2. arrForagers.get(1).start();
3. arrForagers.get(2).start();
 
These 3 Threads run on the same data, and i would not want one of them to have any priority over the others...
What happens today is that #1 is ending and only then i am waiting for #2 to end and #3, which results in the first thread doing most of the work (they are working on the same data, with synchronize on the updated blocks of the code)...
if i would for example do the loop backwards meaning:
1. arrForagers.get(2).start();
2. arrForagers.get(1).start();
3. arrForagers.get(0).start();
The result would be completly diffrent....
might this have to do with the rest of the architecture of my thread class implementation? basiclly in my run i have the code in the attached code sample... i then create these threads and run them...

public boolean pickupFood(Food f)
{	 synchronized (f)
	{
		if (!(f.isPickedup()))
		{
			println(this.name + " picking up " +f);
			f.setPickedup(true);
			return true;
		}
		return false;
	}
}	

public boolean isPickedup() {
	return pickedup;
}
public void setPickedup(boolean pickedup) {
	this.pickedup = pickedup;
}

Open in new window

0
 
LVL 92

Accepted Solution

by:
objects earned 2000 total points
ID: 33516237
order doesn't matter as join() will only return when that thread is finished
so you loop will only finish when all the threads are finished, regardless of what order they start or finish.

I've got an example of using CountdownLatch which I'll post for you, but the result will be the same as using join()
0
 

Author Comment

by:Avir
ID: 33516255
Ok so basiclly my join is correct and does not prioritize any of the threads from your latest response...
 
Thanks for the response
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses

719 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question