Java,将主类传递给子类,编码风格不好?

发布于 2024-10-03 14:18:47 字数 1444 浏览 1 评论 0原文

请耐心等待我,因为我仍在掌握 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);
    }

}

谢谢。

Please bear with me on this as I'm still getting the hang on Java.

The example bellow reads from a Class named Parent that creates an instance of itself on the main method. It then makes that instance do all sorts of calculations.

Next it fires up a thread named Child passing the Parent instance as a reference to Child.

The Child just sits there monitoring things and, sometimes, fires up public methods on Parent.

It works. The question is, is this poor style? Is there a more Java thinking way of doing this sort of work?

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

}

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

倾城花音 2024-10-10 14:18:47

子类化 Thread 被认为是不好的风格。最好实现 Runnable,然后将 runnable 交给线程(嗯......与您的父/子交接非常类似!)。

Runnable r = new Child(parent);
new Thread(r).start();

否则你的 Child.java 代码对我来说看起来很好。

要实现 Runnable,你只需要提供一个 run() 方法:

public class Child implements Runnable {
  private Parent parent;

  public Child(Parent parent) { this.parent = parent; }

  public void run() {
    // what the thread does goes in here...
  }

Subclassing Thread is considered bad style. It's better to implement Runnable, and then hand the runnable off to a thread (hmmm... quite analogous to your Parent/Child hand-off!).

Runnable r = new Child(parent);
new Thread(r).start();

Otherwise your Child.java code looks fine to me.

To implement Runnable you just need to provide a run() method:

public class Child implements Runnable {
  private Parent parent;

  public Child(Parent parent) { this.parent = parent; }

  public void run() {
    // what the thread does goes in here...
  }
一袭水袖舞倾城 2024-10-10 14:18:47

问题是,这样的风格是不是很糟糕?是否有一种更具 Java 思维的方式来完成此类工作?

向“子”对象传递对其“父”对象的引用既不是好样式也不是坏样式。这只是编程。

在真实的应用程序(而不是高度人为的示例)中,您可以判断这是否是良好的设计。

The question is, is this poor style? Is there a more Java thinking way of doing this sort of work?

Passing a "child" object a reference to its "parent" is neither good style or bad style. It is just programming.

In a real application (rather than your highly artificial example) you could make a judgement as to whether or not this was good design.

季末如歌 2024-10-10 14:18:47

除了 朱利叶斯·戴维斯' 答案,我对这样的代码还有另一个担忧:

    Child child = new Child(parent);

即,为什么子进程在自己的线程中,以及子进程将如何处理父进程?

如果父线程确实像看起来那么微不足道,那么子线程似乎就没有必要了。另一方面,如果父线程在子线程启动后执行更多工作,则需要处理同步问题。你必须处理它们。墨菲定律指出,任何可能发生的线程问题都会发生。 (Corallary:即使您是墨菲定律专家,可能的线程问题也比您意识到的要多。)

编辑:好的,子线程调用 parent.getDataFromChild< /代码>。该方法对数据有何作用? (它是否会对从主线程访问的对象进行任何更改?)由于它是从子线程调用的,因此您需要检查父类和子类是否存在可能的竞争条件。

In addition to Julius Davies' answer, I have another concern about code like this:

    Child child = new Child(parent);

Namely, why is the child in its own thread, and what is the child going to do with the parent?

If the parent really is as trivial as it appears to be, then the child thread doesn't seem to be necessary. On the other hand, if the parent does more work after the child thread is started, then you have synchronization issues that you need to deal with. And you must deal with them. Murphy's Law says that any threading problems that can happen, will happen. (Corallary: There are more possible threading issues than you're aware of, even if you're an expert on Murphy's Law.)

EDIT: OK, the child thread calls parent.getDataFromChild. What does that method do with the data? (Does it make any changes to objects that are also accessed from the main thread?) Since it's called from the child thread, you need to inspect both the parent and child classes for possible race conditions.

香橙ぽ 2024-10-10 14:18:47

除了 Child 类应该实现 Runnable 之外,我没有发现任何问题。只要您记录了 ParentChild 之间的关系,它看起来就很好。

I don't see anything wrong with this except the Child class should implement Runnable. As long as you document the relation between Parent and Child it looks fine.

行雁书 2024-10-10 14:18:47

如果子对象在其他地方被引用,您将需要重写父对象的 Finalize 方法来清理子对象。否则,我似乎完全可以接受。

You'll want to override the finalize method on the parent to clean up Child if they're referenced elsewhere. Otherwise it seems perfectly acceptable to me.

錯遇了你 2024-10-10 14:18:47

关于您所写的内容,最好让 Child 在线程中运行

http: //www.javabeginner.com/learn-java/java-threads-tutorial

然后关于这是否是一个好方法的问题答案是:这取决于你想做什么哈哈

你可以研究几件事:

  • 捕获各种异常,例如

中断异常

  • 读取同步以防止同时访问/修改。

  • 您可以检查观察者类/设计模式来控制线程何时唤醒以进行测试,而不是睡眠

,我想向您介绍一下用 Java 线程化您的应用程序的美妙世界:D

编辑:正如 Dave L 所指出的,您需要注意清理您引用的内容,否则您最终会遇到僵尸节目^^

Regarding what you wrote it is better for Child to be Runnable that runs in a Thread

http://www.javabeginner.com/learn-java/java-threads-tutorial

then regarding the question of whether it is a good way the answer is : it depends what you want to do LOL

You can look into several things:

  • Catching various exceptions like

InterruptedException

  • reading up a synchronized to prevent simultaneous access/modifications.

  • instead of sleep you can check the observer class/design pattern to control when your threads wake to do there tests

Finally I would like to great you to the wonderful world of Threading your app in Java :D

Edit: as Dave L pointed out as well you need to pay attention to clean up what you reference otherwise you'll end up with zombies in you program ^^

我还不会笑 2024-10-10 14:18:47

我从你的代码中读到的是循环依赖,这是不好的。

您可以使用接口来消除依赖性。

What I read from your code is a cycle dependency which is bad.

You may make use of interfaces to remove the dependency.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文