【发布时间】:2010-11-17 04:11:41
【问题描述】:
请多多包涵,因为我还在学习 Java。
下面的示例从名为 Parent 的类中读取数据,该类在 main 方法上创建自身的实例。然后它使该实例进行各种计算。
接下来它会启动一个名为 Child 的线程,将 Parent 实例作为对 Child 的引用。
Child 只是坐在那里监视事物,有时还会在 Parent 上启动公共方法。
它有效。问题是,这是不是很糟糕的风格?有没有更多的Java 思维方式来做这种工作?
public class Parent {
// main function that fires up the program
public static void main() {
// creates an instance of himself
// and fires go that does all sorts of fuzzy calculus
Parent parent = new Parent();
parent.go();
// creates a new thread of child and starts it
Child child = new Child(parent);
child.start();
}
private void go() {
// all sort of initializations
}
public void getDataFromChild(int data) {
// will get data from running child thread
}
}
public class Child extends Thread {
private Parent parent;
// child constructor grabs Parent instance into "o"
public Child(Parent o) {
parent = o;
}
// this class main loop
public void run() {
while(1==1) {
doSomething();
try {
sleep(1000);
}
catch(Exception e) { }
}
}
private void doSomething() {
parent.getDataFromChild(1);
}
}
谢谢。
【问题讨论】:
-
应该有办法终止子线程(但也许无限的while循环只是一个简化的例子)。
标签: java implementation