开发者

Keeping track of threads when creating them recursively

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 i开发者_运维问答n 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.


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();
}


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!


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜