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
  • 399,198
  • 105
  • 792
  • 807
user3571396
  • 103
  • 2
  • 11
  • check this out .... http://stackoverflow.com/questions/14808895/thread-not-calling-run-method – Aditya Peshave Mar 28 '15 at 19:14
  • @user3571396, since you're new to StackOverflow, you may want to read [this](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work). – aioobe Mar 31 '15 at 10:02

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
  • 399,198
  • 105
  • 792
  • 807
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
  • 2,975
  • 2
  • 25
  • 49