Search code examples
javajava-threads

run method in Thread class


The output is : RunnableA ThreadB
I don't understand how it comes?? (what happens in the run method in class B)

class A implements Runnable{
    public void run(){
        System.out.println("RunnableA");
    }
}
class B extends Thread{
    B(Runnable r){
        super(r);
    }
    public void run(){
        super.run();
        System.out.println("ThreadB");
    }
}
class Demo{
    public static void main (String []args){
        A a=new A();
        Thread t=new B(a);
        t.run();
    }
}

Solution

  • See carefully the implementation of the run method of Thread class its as under :

      public void run() {
        if (target != null) {
            target.run();
        }
        }
    

    So calling the run method of Thread calls the run of the Runnable that is passed , In your case you have passed the instance of A while creating Thread t . So call to super.run() calls the run method of Thread class which in turns calls the run method of the A(which is runnable or the target).