문제

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();
    }
}
도움이 되었습니까?

해결책

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).

다른 팁

As you call super.run() in B#run it will execute Thread#run and next run method of of the instance of Runnable you passed to the constructor will be executed.

Thread.run simply calls the run method of the Runnable implementation you gave it. But you should NEVER call Thread.run, instead call Thread.start.

Because You have subclass B and overridden its method run().

It'll call B's method first.

and in B's run() it find the super call so it calls super's run() (which will execute the provided Runnable's run()) first and then execute B's run()

when you created the object of class B and passed a to it ,the constructor of class b was called .Whats in B's constructor ? super(r); this sets r to be the super call. now in main when you say t.run() it call the overridden method of class B which calls the the run method of the object you have binded super with by saying super(r) .so the run method of a is called first and then "ThreadB" is printed.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top