Java Thread: an overriding example code

class A implements Runnable {
    public void run() {
        System.out.println(Thread.currentThread().getName());
    }
}
 
class B implements Runnable {
 
    public void run() {
        new A().run();
        new Thread(new A(), "name_thread2").run();
        new Thread(new A(), "name_thread3").start();
    }
}
 
public class Main {
 
    public static void main(String[] args) {
        new Thread(new B(), "name_thread1").start();
    }
}

What is the output?

============================
name_thread1
name_thread1
name_thread3
============================ 

The difference between “new Thread(new A(),”name_thread2″).run(); ” and “new Thread(new A(),”name_thread3″).start();” is that the start() method creates a new Thread and executes the run method in that thread. If you invoke the run() method directly, the code in run method will execute in the current thread. This explains why the code prints two lines with the same thread name.

1 thought on “Java Thread: an overriding example code”

Leave a Comment