Solved

How to preform Multi Thread Join Async

Posted on 2010-08-24
9
480 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
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

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 500 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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
jdbc error in jsp application 20 63
ejb mdb examples 1 8
Why doesn't this text field show up on my Applet frame? 2 19
Notify sent to other threads in Java 9 33
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…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
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…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

856 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