Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a java.lang.Thread not call the run() method of its explicit java.lang.Runnable when started?

The Java docs state that if we supplied a Runnable target when creating a new thread, .start() of that thread would run the run() method of the supplied runnable.

If that's the case, shouldn't this test code prints "a" (instead of printing "b") ?

public class test {
    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.println("a");
            }
        };
        Thread t = new Thread(r) {
            @Override
            public void run() {
                System.out.println("b");
            }
        };
        t.start();
    }
}
like image 981
Pacerier Avatar asked Dec 23 '11 17:12

Pacerier


2 Answers

Because you are overriding Thread.run() method.

Here is the implementation of Thread.run():

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

try:

}) {
    @Override
    public void run() {
        super.run(); // ADD THIS LINE
        System.out.println("b");
    }
}.start();

You will get ab.

like image 91
user802421 Avatar answered Nov 15 '22 07:11

user802421


The default implementation is to call the Runnable. However you are overriding the default implementation and NOT calling the runnable. The simplest way to fix this is

    new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("a");
        }
    }) {
        @Override
        public void run() {
            super.run(); // call the default implementation.
            System.out.println("b");
        }
    }.start();
like image 29
Peter Lawrey Avatar answered Nov 15 '22 07:11

Peter Lawrey