new Thread(new Main(), "a").start(); new Thread(new Main(), "b").start();
Is there any difference between the above code and the following code? What’s the difference?
Main a=new Main("A"); Main b=new Main("b"); a.start(); b.start();
1. You just need to ask:
new Thread(new Main()).start(); And new Main().start();
The difference between these two ways of creating threads is sufficient, which can better reflect the essence of the problem, so there is no need for which A and B come out. I feel that this is a principle for asking questions. Like unit tests, you should go straight to the point of what you want to do, and don’t add irrelevant things to disturb your sight.
2. Main in the first code is the implementation of a Runnable interface, and the second Main is an extension of a Thread class. These are two different ways to implement threads in Java, so the question can be abstracted as: What are the differences between these two different thread implementations in Java?
3. I understand that the difference between the two implementations is: using the way to implement the Runable interface
A) you can inherit other classes, but you can’t inherit other classes by inheriting the Thread class (java can only inherit singly).
B) More importantly, the sharing of resources among threads can be realized.