0

I just want to understand how below code snippet work ?

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

Output - Rocky is here

aioobe
  • 413,195
  • 112
  • 811
  • 826
user3571396
  • 113
  • 2
  • 11

2 Answers2

3

There's not much to explain.

  • You override start() with code that prints Rocky is here
  • then you call start() which prints Rocky is here.
  • (the run method is never involved)

People often confuse the purpose of start and run. See for instance this question:

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

The rules are simple:

  • Thread.run is an ordinary method (no magic)

  • Thread.start contains some magic because it spawns a separate thread (and lets that thread invoke run).

    • If you override Thread.start with your own method, then there's no magic left anywhere.
Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
0

what you have here is a Java class which extends the Thread class (http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html)

class AnnaThread extends Thread {

then in your main method you create a new instance of the class which is a Thread (since the class extends the Thread)

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

then you call the method start which follows bellow

        t.start();

which prints

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

you could as well call the other method if you add the following line in your code

      t.run();

in which case the method run would be executed which would print

        System.out.println("Anna is here");
adrCoder
  • 3,145
  • 4
  • 31
  • 56