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.

Category >> Concurrency  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>

  1. […] Create thread by overriding(another way, difference) […]

Leave a comment

*