Solved

How to preform Multi Thread Join Async

Posted on 2010-08-24
9
473 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
 

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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

Suggested Solutions

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

747 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now