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(); } } }
run
super.run()
in the redefinedrun
. - VladD pm