Hello! I decided to experiment with Thread, what kind of run will be launched, but I don’t know why this is the case. The essence is as follows: I create a child class from Thread, and “as I define” in it two run methods — the first with the internal anonymous Runnable class is passed to the constructor, and the second run method is simply overridden, like this:

class MyThread extends Thread{ MyThread (){ super(new Runnable(){ public void run(){ //=================== first run System.out.println("first run"); } }, "MyThread"); System.out.println(" сработал конструктор"); start(); } @Override public void run (){ //=================== second run try { for(int i=1;i<5;i++){ System.out.println(i+" second run. Текущий поток "+Thread.currentThread()); Thread.sleep(500); } } catch (InterruptedException e ){ e.printStackTrace();} } } 

Then I run in the main thread and it is the run that is triggered that is the second one that was redefined, and not the one that was passed to the constructor. Sorry if the question is stupid, but who can explain why this is happening? Or tell me where you can read about it. Thank!

 public class Main { public static void main(String[] args) { new MyThread(); try { for(int i=1;i<5;i++){ Thread.sleep(1000); } } catch (InterruptedException e ){ e.printStackTrace(); } } } 
  • This is nothing, you try to run super.run() in the redefined run . - VladD pm

1 answer 1

In a separate thread, the run() method of the Thread class is executed, it is written here . And if you look at the implementation of OpenJDK Thread , you can see:

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

Those. if you passed in the Runnable constructor, then it will call it. You have redefined the run() method and accordingly it does something for you.

  • one
    Yes, but I also passed the constructor Runnable, and the class overloaded. - Stanly T
  • 3
    @MisterSmith, once again: you redefined the original run method, there is no more for the thread, and your run method does not know anything about Runnable from the constructor - Nofate