Java we want to implement multithreading commonly used in two ways, inherit the thread class and implement the Runnable interface, experienced programmers will choose to implement Runnable interface, the main reason for the following two points:
First, Java can only be inherited only, so if you are using the method of inheriting thread, you may encounter problems in later refactoring because you cannot inherit other classes.
Second, if a class inherits thread, it is not appropriate for resource sharing. However, if the Runable interface is implemented, it is easy to achieve resource sharing.
The difference between the two approaches can be clearly seen through the example below. 1. Inherit Thread class
Package test;
/**
* Inheritance Thread class
* @author hongxin
* * */public
class Testthread extends thread{
private int count=5;
private String name;
Public Testthread (String name) {
This.name=name
}
public void Run () {for
(int i = 0; i < 5; i++) {
System.out.println (name + "Run count=" + count--);
try {sleep
(int) math.random () *);
\ catch (interruptedexception e) {
e.printstacktrace ();
}
}
}
}
Package test;
public class Main1 {public
static void Main (string[] args) {
testthread mth1=new testthread ("A");
Testthread mth2=new testthread ("B");
Mth1.start ();
Mth2.start ();
}
Run Results
Code Analysis
The variables between thread 1 and thread 2 are not shared, and each count--has its own variables and results.
2.Runnable Interface
Package test;
/**
* Implements Runnable interface
* @author hongxin * */Public
class Testrunnable implements runnable{
private int count=15;
@Override public
Void Run () {for
(int i = 0; i < 5; i++) {
System.out.println (thread.currentthread). GE Tname () + "Run count=" + count--);
try {
thread.sleep (int) math.random () *);
catch (Interruptedexception e) {
e.printstacktrace (); c28/>}}}
Package test;
public class Main2 {public
static void Main (string[] args) {
testrunnable mTh = new testrunnable ();
New Thread (mTh, "C"). Start ()//the same mTh, but not in Thread, if you use the same instantiation object MT, an exception
new thread (mTh, "D") appears. Start ();
New Thread (MTh, "E"). Start ();
}
Run Results
Code Analysis
The variables between three different threads are shared, and each count--gets a demerit from the previous thread's running results.