Use Thread Classes and Runnable Interface to achieve the difference between multithreading
Let's first look at the steps of the two implementation methods :
public class ThreadDemo{
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
// Create and start inherited by Thread Class created thread
new Thread(new MyThread(),"Thread"+i).start();
// Create and start by implementing Runnable Interface created thread
new Thread(new Runner(),"Thread"+i).start();
}
}
}
// Inherit Thread class
class MyThread extends Thread{
// rewrite run Method
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" Inherited by Thread establish ");
}
}
// Realization Runnable Interface
class Runner implements Runnable{
// Realization run Method
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" There is realization Runnable Interface to create ");
}
}
As you can see from the code above , When using Runnable Interface when creating multithreads , You need to enter and exit the implementation class as a parameter to Thread In the instance object , By calling Thread Object's start Method to start . Let's take a look Thread Source code
//Thread Class inherited Runnable class
public class Thread implements Runnable {}
//Thread The constructor of called init Method
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
//init Static method called init
private void init(ThreadGroup g, Runnable target, String name,
long stackSize) {
init(g, target, name, stackSize, null, true);
}
// Look at the static method init
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc,
boolean inheritThreadLocals) {
...
// private Runnable example
this.target = target;
...
}
// Look again. Runnable Method
@Override
public void run() {
if (target != null) {
target.run();
}
}
From the above process of tracking the source code, we can see ,Thread Class implements the Runnable Interface , And inheritance Thread Class rewriting run The essence of method is to realize Runnable Interface run Method .
Through the above analysis , Summarize the use of Thread Classes and Runnable Interface differences :
- Using inheritance Thread Class implements multithreading compared to Runnable It's simpler , Use Runnable The interface needs to use Thread Encapsulate again .
- because Java Multiple inheritance is not supported in , A class inherits Thread Class cannot inherit other classes , Therefore use Runnable Interface implementation of multithreading has better flexibility .
In addition to the above two multithreading implementation methods , You can also use Callable Interface implementation , I wrote an article about Callable and Runnable Interface implementation of multi-threaded comparison summary :
Use Runnable and Callable Interface to achieve the difference between multithreading