1. Creation of threads
Prior to knowing that a multithreaded creation method in Java is to inherit the thread class or implement the Runable interface, but can not understand the following method of creating threads
First Kind
[Java]View PlainCopyprint?
- New Thread (new Runnable () {
- @Override
- public Void Run () {
- }
- }
- }). Start (); The new Thread () in this way creates a thread, and the new Runable () object is the code that the thread wants to execute, putting the code that you want to execute into a created object,
[Java]View PlainCopyprint?
- <span style="White-space:pre" > </span> //To well embody the object-oriented programming rules.
or the following creation format
The second Kind
[Java]View PlainCopy print?
- new thread () {
- @Override
- public void run () {
- // TODO auto-generated method stub
- super.run ();
- }
- &NBSP;&NBSP;&NBSP;&NBSP;}. Start ();
In fact, two methods yesterday saw a video is now understood, in fact, the first method is the object-oriented thinking mode to create a thread, in the source code of thread, one is through the construction method to pass a Runable object and then assign a value to target, and then to implement a thread creation, That is, the first way to create a method, is to directly rewrite the Run method, which is the second method above to create a thread, but the Internet is usually the first method to use more? What's that for? Because the first way to create a thread by constructing a method is to have a more oriented rule, the new thread () creates an object, and the code that the object wants to execute is written in parentheses, which is a good representation of object-oriented programming.
So let's think about how the next way to create an object would be to execute the Run method in Runable or execute the thread's Run method?
[Java]View PlainCopyprint?
- New Thread (
- New Runnable () {
- public Void Run () {
- While (true) {
- try {
- Thread.Sleep (500);
- } catch (Interruptedexception e) {
- E.printstacktrace ();
- }
- System.out.println ("runable" + thread.currentthread (). GetName ());
- }
- }
- }
- ) {
- @Override
- public Void Run () {
- While (true) {
- try {
- Thread.Sleep (500);
- } catch (Interruptedexception e) {
- E.printstacktrace ();
- }
- System.out.println ("thread" + thread.currentthread (). GetName ());
- }
- }
- }.start ();
New Thread (New Runable () {}) {}.start (); The answer is to execute the Run method in Thread (that is, the Run method in the subclass). Since the run () method in the parent class is overridden when creating a new thread, the Run method in thread is executed directly, and the Run method in the parent class is executed if the Run method in the subclass does not exist.
Better understanding of Java multithreading