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();
}
}
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With