Java thread: overridding 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?
============================
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();”:
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 will execute in the current thread. This also expains why your code prints two lines with the same thread name.

You may also like:

Leave a comment