Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

How to preform Multi Thread Join Async

Posted on 2010-08-24
9
Medium Priority
?
486 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
  • 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

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

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!

Question has a verified solution.

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

For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Suggested Courses

782 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