I have a tree structure that I am trying to use a recursive method to add, get, or remove an item. I would like to be able to introduce a new thread for every child node that I find with an iterator. I currently pass the node into the recursive method when I call it. I would like to be able to start a thread and tell that thread to call that method. How would I do something similar to saying new thread, thread.callMethod()? I need to have a Runnable interface and a run method apparently? However this seems to complicate things much more than necessary (I already have method names). Does anyone know a good way to do this using run(..), or does anyone know a better way to do this without using run(..). Thanks.
Thank you for your answers. I had been thinking that I need to somehoe get a new instance of a node running on a new thread, but that is not the case. The node just occupies space in memory and the thread is reference to the method code that is executed on the instance living in memory (my CS 302 TA is already disagreeing with me in my head). So.. I had been thinking about enums, but I was thinking that I might somehow need to have all my nodes running on separate threads during instantiation, or else, have the methods actually written in new classes that implement runnable.
In other words,
public class TreeMethods implements Runnable
{
...
run(.. node, .. params, .. enum)
{
switch(enum)
case(add)
{
myThreadInstanceMethod(node);
}
...
}
myThreadInstanceMethod(..) {..}
}
Thanks. I didn’t know that I was asking this question, but you’ve just simplified my thread management design process greatly.
You can’t do it without a
RunnableorCallableobject. The proper way to do what you want is to create aRunnableclass that takes your object and calls the appropriate method on that object.If you need to call one of a couple methods then you can use an
enumfor this. If you need to pass in arguments then you can add them to the constructor.With threads, it’s always recommended that you use the
Executorsclass and theExecutorServicethread pools. This will limit the number of threads created by your recursive algorithm and keep the thread particulars hidden.