First, multithreading is implemented in two ways: one is to inherit the thread class, the other is to implement the Runnable interface.
So what's the difference between the two methods? How to choose.
first: The relationship between them
View the Java EE API to see
Thread class: public class Thread extends Object implements Runnable
Runnable Interface: Public interfacerunnable
Clearly know both: the thread class is an implementation class of the Runnable interface, so what is the Runnable interface?
Document Explanation:
The Runnable interface should be implemented by classes that intend to execute their instance through a thread. Class must define a parameter-free method called run.
The purpose of designing this interface is to provide a public protocol for objects that you want to execute code at activity time. For example, the Thread class implements Runnable. Activation means that a thread has started and has not stopped.
That is to say, Runnable provides a thread-running specification, which needs to be implemented by its implementation class
Second: Through the source analysis
We use the public class Thread1 extends thread to trace the custom thread: First view the Thread class
Which defines a private Runnable target; Attribute target with the runnable type defined to see where there is a reference
Several methods:
private void Init (Threadgroup g, Runnable Target, String name,
long stacksize) {... }
Public Thread () {
init (null, NULL, "thread-" + nextthreadnum (), 0);
Public
Thread (Runnable target) {
init (null, Target, "thread-" + nextthreadnum (), 0);
}
Public Thread (Threadgroup Group, Runnable target) {
init (group, Target, "thread-" + nextthreadnum (), 0);
}
Public Thread (String name) {
init (null, NULL, name, 0);
}
Public Thread (Threadgroup Group, String name) {
init (group, NULL, name, 0);
}
Public Thread (Runnable target, String name) {
init (null, target, name, 0);
}
Public Thread (Threadgroup Group, Runnable Target, String name) {
init (group, target, name, 0);
}
Public Thread (Threadgroup Group, Runnable Target, String name,
long stacksize) {
init (group, target, name, StackS ize);
}
The above list contains an initialization method for thread init () and all construction methods: You know, the constructor needs to invoke the Init () method to initialize the thread object, and a target object of the Runnable type participates in initialization.
The thread class that we know is running threads is calling the start () method, and we're also looking at this method:
Public synchronized void Start () {/** * the ' is not ' invoked for the
' main method thread or ' system '
* g Roup threads Created/set up by the VM. Any new functionality added
* "to" in "future may have to also is added to the VM."
*
A Zero status value corresponds to state "NEW".
*/
if (threadstatus!= 0)
throw new Illegalthreadstateexception ();
Group.add (this);
Start0 ();
if (stopbeforestart) {
stop0 (throwablefromstop);
}
}
When this start () method is invoked, the thread starts executing, and the Java virtual machine invokes the thread's Run method. The result is that two threads run concurrently, when the line (returned from the call to the Start method) and another thread (executes its Run method). This method is only judged on the thread state (ensuring that a thread does not start multiple times, starting more than once in the JVM's view that this is illegal), and then adding the thread to the thread group (not much explanation) and waiting to run.
So keep looking at the run () method:
public void Run () {
if (target!= null) {
target.run ();
}
}
When the Runnable implementation class object does not have null content, the method does nothing, and if there is an implementation class object, it is invoked to implement the run () method of the Class object implementation. This reminds us of a classic design pattern: proxy mode
So we know that the thread is running on the start () method in the thread class, and the run () method is called by the virtual machine, so we have to implement the run () method
Well, let's take a look at the design of the Runnable interface:
Public
interface Runnable {
/**
* If an object implementing interface <code>Runnable</code> is used
* To create a thread, starting the thread causes the object ' s
* <code>run</code> Called in that separately executing
* thread.
* <p> * The general contract of the "method
<code>run</code>" It may
* take any action WHA Tsoever.
*
* @see java.lang.thread#run () * */public
abstract void Run ();
}
It only has an abstract run () method, which is a completely real thread-running specification
Third: Through the design pattern between them: The agent mode again deep
Agent mode as shown:
Thread is also a subclass of the runnable interface, but it does not fully implement the run () method, so it is still necessary to overwrite the run () method if the inheritance thread class implements multiple threads.
Look at two basic ways to achieve multithreading
Inherit thread:
Class Mythread extends thread{
private int ticket = 5;
public void Run () {
for (int i = 0;i<100;i++) {
if (ticket>0) {//Judge if there is any remaining ticket
System.out.println ("sell tickets, Ticket = "+ticket--);
}}}
;
public class threaddemo04{public
static void Main (String args[]) {
Mythread mt1 = new Mythread ();
Mythread mt2 = new Mythread ();
Mythread mt3 = new Mythread ();
Mt1.start ();//The calling thread body lets it run
mt2.start ();//Three places sell tickets at the same time
Mt3.start ();
}
;
Implement runnable:
Class Mythread implements runnable{
private int ticket=5;
public void Run () {
for (int i = 0;i<100;i++) {
if (ticket>0) {
System.out.println ("sell tickets, ticket =" + ticket--);
}}}
;
public class runnabledemo02{public
static void Main (String args[]) {
Mythread my1 = new Mythread ();
New Thread (MY1). Start (); Start three threads
new Thread (MY1). Start ()///Share resource
new Thread (MY1) in my1. Start ()
;
Finally: regardless of which method needs to implement the run () method, the Run method is the running body of the thread. Also, the thread's run is the start () method that invokes thread.
The thread class in proxy mode acts as a proxy class, and it does something before the thread run body runs and then runs the Threads Run (). First of all, the basic characteristics of the agent model is to "enhance the proxy target" agent mode is not detailed here. In summary, thread provides a lot of action before and after the thread runs, and then uses its start () method to let the JVM automatically invoke the target's run () method
Fourth: The difference between inheriting thread and implementing Runnable interface method
First look at a piece of code:
New Thread ( new Runnable () { public void Run () { while (True) { & nbsp; try {
Thread.Sleep (500); } catch (Interruptedexception e) { E.printstacktrace (); }
System.out.println ("runnable:" + thread.currentthread (). GetName ()); }  } & nbsp;  }) { public void Run () { while (true) { & nbsp try {
thread.sleep (500);
 } catch (Interruptedexception e) {e.printstacktrace ();}
System.out.println ("Thread:" + thread.currentthread (). GetName ());
}  }}.start ();
You can predict which run () method the code is executing.
Based on previous Java basics: After the start () method, the JVM goes to the run () method, and then it finds its own run () method, and runs its own run () method directly. If you can't find your own method, it will find the agent's run () method. So what it should do is "thread: ..." "Code section. You can put it in a main method and infer it correctly through test validation:
To illustrate is an object-oriented idea: if there is no upper second run () block, then it performs the anonymous Runnable implementation class's Run () method. What this means is that thread is equivalent to a performer, and the code blocks that are executed are defined in the Runnable implementation class. This implementation and the separation of the source code, embodies the idea of object-oriented. This is also a big difference between them.
Other differences:
Implement runnable interface to achieve resource sharing, thread cannot complete resource sharing-----Discussion 3rd of the two code: inherit thread: The result sold 15, each with the votes. How to implement the Runnable interface: Sell 5 pieces and share resources
Implementing the Runnable interface than inheriting the thread class to achieve multithreading has the following obvious advantages:
The use of common resources for multiple identical program codes;
Avoid the impact of the limitations of single inheritance;
Enhance the robustness of the program, the code can be shared by multiple threads, the code data is independent;
Selection of Use
By comparison of the differences between:
Because object-oriented thinking, as well as resource sharing, code robustness, and so on, generally using the implementation of Runnable interface to achieve multithreading, but also more recommended
Above for multithreading a little personal summary, later continue to keep up. If there are any improper representations, thank you for your DMS point out that I will resolve them as soon as possible