【发布时间】:2009-01-21 06:07:44
【问题描述】:
我有一个连接到数据库的DBAdmin 类,然后还有一些其他类,例如Article、Category 等等,它们对数据库执行某些查询。
我在 Swing 应用程序中使用这些类来构建一种小型 Intranet CMS 应用程序。
现在,Category 类有一堆static 方法,例如addCategory、editCategory 等等,像这样:
public class Category implements Runnable {
public void run () {
//Code that will be executed in a separate thread, from the Runnable Interface
}
public static int addCategory(Category cat) {
DBAdmin db = DBAdmin.getInstance();
db.connectDB();
//rest of the code that creates sql statement and so on...
}
//Other static edit and delete methods that will be called from outside
}
附: DBAdmin 是一个单例类,getInstance 方法返回自调用的实例。
现在,我想做的是数据库操作应该在与应用程序不同的线程中运行,并且我设法在run 方法中运行一些示例测试Thread是started。
但问题是我无法指定在启动线程时应该在run方法中运行哪个方法。
从某种意义上说,例如,当从外部调用 addCategory 时,run 方法应该调用其中的 addCategory 方法。
有没有办法将一个函数作为回调参数从addCategory 方法传递给run 方法,以便它知道当一个新线程启动时应该在其中调用哪个函数?还是有完全不同的方式来实现我想要做的事情?
附:在这一点上,我对 Java 还“相当”陌生,尤其是多线程,所以我可能在这里遗漏了一些东西。
【问题讨论】:
标签: java multithreading singleton