方法首选项如何在java中工作?

时间:2015-03-28 19:11:00

标签: java

我只是想了解下面的代码段如何工作?

class AnnaThread extends Thread {

    public static void main(String args[]){
        Thread t = new AnnaThread();
        t.start();

    }

    public void run(){
        System.out.println("Anna is here");
    }
    public void start(){
        System.out.println("Rocky is here");
    }
}

输出 - 洛基在这里

2 个答案:

答案 0 :(得分:3)

没有太多要解释的。

  • 您使用打印start()
  • 的代码覆盖Rocky is here
  • 然后拨打start(),打印Rocky is here
  • (从不涉及run方法)

人们常常混淆startrun的目的。例如,请参阅此问题:

Why we call Thread.start() method which in turns calls run method?

规则很简单:

  • Thread.run是一种普通的方法(没有魔法)

  • Thread.start包含一些魔法因为它产生了一个单独的线程(并让该线程调用run)。

    • 如果您使用自己的方法覆盖Thread.start,那么任何地方都没有任何魔力。

答案 1 :(得分:0)

这里有一个Java类,它扩展了Thread类(http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html

class AnnaThread extends Thread {

然后在您的main方法中,您创建了一个new instanceThread(自class extends the Thread起)

    public static void main(String args[]){
        Thread t = new AnnaThread();

然后你调用下面的方法开始

        t.start();

打印

System.out.println("Rocky is here");

如果在代码中添加以下行,也可以调用其他方法

      t.run();

在这种情况下,将执行方法运行,这将打印

        System.out.println("Anna is here");