views:

58

answers:

3

I'm currently working on some code for a course. I can't post the code but I'm permitted to talk about some high level concepts that I'm struggling with and receive input on them. Basically the code is a recursive DFS on a undirected graph that I'm supposed to convert to a concurrent program. My professor already specified that I should create my threads in the recursive DFS method and then join them in another method. Basically, I'm having trouble thinking of how I should keep track of the threads I'm creating so I can join all of them in the other method. I'm thinking an array of Threads but I'm unsure how to add each new thread to the array or even if that's the right direction.

A: 

That sounds correct, you'll want a list of threads. Since you'll be accessing the list/array from multiple threads, you could use one of the thread-safe list classes, or have an "addThread(Thread newlyCreatedThread)" method which is synchronized. Hope this helps!

Jon
Thanks. So something like ArrayBlockingQueue would probably be a good idea? I didn't think about my list being thread-safe.
66replica
BlockingQueue is a threadsafe way to pass stuff around. Is your list changing mid iteration? If not, then you don't need to worry about the thread saftey of how you distribute the work. Thread saftey of which threads are running, yes.
bwawok
A: 

You could create a new ThreadGroup object in your main application thread and then make all of your spawned threads members of it. You just have to be wary of the oddball semantics of the enumerate method on the ThreadGroup when you try to get them back. (read the javadoc carefully!)

What is the purpose of joining them anyway? Just to find out if they're done? Perhaps learning about implementing the Delegate pattern in Java with interfaces would be helpful.

Affe
So I don't print the spanning tree before all threads have returned I assume.
66replica
Ah, I suppose more information about how the threads are aggregating their results would be needed to provide more intelligent advice. If joining them from the main application thread is the method specified for the assignment, no merit in over-thinking it!
Affe
I think this is the most elegant solution. I'll then loop while (activecount > 0) to join them. Thanks.
66replica
+1  A: 

Another way to achieve this is with a BlockingQueue and a ThreadPoolExecutor. You can continously add new threads to the BlockingQueue, keep a count of how many you added and then shutdown the ThreadPoolExecutor when you are done.

private ThreadPoolExecutor pool;
private BlockingQueue<Runnable> queue;
...
this.pool = new ThreadPoolExecutor(10, 10, new Long(1000), 
                TimeUnit.MILLISECONDS, this.queue);
...

//new thread created and added to the queue
requestedTasks++

if (requestedTasks == this.pool.getCompletedTaskCount() && this.queue.isEmpty()) {
  this.pool.shutdown();
}
Lars Andren