我有一个树结构,我试图使用递归方法来添加、获取或删除项目。我希望能够为我通过迭代器找到的每个子节点引入一个新线程。目前,当我调用递归方法时,我将节点传递给它。我希望能够启动一个线程并告诉该线程调用该方法。我将如何做类似于新线程 thread.callMethod() 的事情?我显然需要一个 Runnable 接口(interface)和一个 run 方法?然而,这似乎使事情变得比必要的复杂得多(我已经有了方法名称)。有谁知道使用 run(..) 执行此操作的好方法,或者有人知道不使用 run(..) 执行此操作的更好方法。谢谢。
谢谢您的回答。我一直在想我需要有人获得在新线程上运行的节点的新实例,但事实并非如此。节点仅占用内存中的空间,线程引用在内存中的实例上执行的方法代码(我的 CS 302 TA 已经在我的脑海中不同意我的观点)。所以..我一直在考虑枚举,但我在想我可能需要在实例化期间让所有节点在单独的线程上运行,或者将方法实际编写在实现可运行的新类中。
换句话说,
public class TreeMethods implements Runnable
{
...
run(.. node, .. params, .. enum)
{
switch(enum)
case(add)
{
myThreadInstanceMethod(node);
}
...
}
myThreadInstanceMethod(..) {..}
}
谢谢。我不知道我在问这个问题,但你大大简化了我的线程管理设计过程。
最佳答案
如果没有 Runnable
或 Callable
对象,您就无法做到这一点。执行您想要的操作的正确方法是创建一个 Runnable
类,该类接受您的对象并调用该对象上的适当方法。
public class MyRunnable implements Runnable {
private MyObject obj;
public MyRunnable(MyObject obj) {
this.obj = obj;
}
public void run() {
obj.someMethod();
}
}
如果您需要调用几个方法之一,那么您可以使用enum
来实现。如果您需要传入参数,则可以将它们添加到构造函数中。
对于线程,始终建议您使用 Executors
类和 ExecutorService
线程池。这将限制递归算法创建的线程数量并隐藏线程详细信息。
// create a thread pool with 10 workers
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// or you can create an open-ended thread pool
// ExecutorService threadPool = Executors.newCachedThreadPool();
while (recursing) {
threadPool.submit(new MyRunnable(myObject));
}
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();
...
关于java - 使用递归和 Java 以及树结构多线程访问添加、获取、删除方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13371809/