In Java, there are two ways to implement multi-threading, one is to inherit the thread class, and the other is to implement the Runnable interface;
Runnable interface
In real-world development, a multithreaded operation rarely uses the thread class, but is accomplished through the Runnable interface.
Class MyThread implements runnable{
However, there is no start () method in a subclass defined with runnable, only in the thread class. At this point the Thread class is observed, and there is a constructor method: public Thread (Runnable target) This construction method accepts Runnable instances of subclasses,
This means that the thread class can be used to start the multithreading of the runnable implementation
Runnable interface: MyThread mt1=new MyThread ("Thread A");
Start runnable:new thread (MT1) by using the Thread class. Start ();
The difference between the two ways of implementation and contact:
In the program development, as long as the multithreading is always to achieve runnable interface-based, because the implementation of runnable interface compared to
Inheriting the thread class has the following benefits:
To avoid the limitations of point inheritance, a class can inherit multiple interfaces.
--Suitable for resource sharing
Take the ticket selling procedure as an example, complete by the thread class:
Package ORG.DEMO.DFF;
Class MyThread extends thread{
private int ticket=10;
public void Run () {
for (int i=0;i<20;i++) {
if (this.ticket>0) {
SYSTEM.OUT.PRINTLN ("Sell ticket: Ticket" +this.ticket--);
}
}
}
};
Below through three thread objects, while selling tickets:
Package ORG.DEMO.DFF;
public class Threadticket {
public static void Main (string[] args) {
MyThread mt1=new MyThread ();
MyThread mt2=new MyThread ();
MyThread mt3=new MyThread ();
Mt1.start ();//each thread sold 10 sheets, sold 30 tickets.
Mt2.start ();//But actually there are only 10 tickets, and each thread sells its own ticket.
Mt3.start ();//failed to achieve resource sharing
}
}
If you can use runnable to achieve resource sharing, see the example below:
Package org.demo.runnable;
Class MyThread implements runnable{
private int ticket=10;
public void Run () {
for (int i=0;i<20;i++) {
if (this.ticket>0) {
SYSTEM.OUT.PRINTLN ("Sell ticket: Ticket" +this.ticket--);
}
}
}
}
Package org.demo.runnable;
public class Runnableticket {
public static void Main (string[] args) {
MyThread mt=new MyThread ();
New Thread (MT). Start ();//the same MT, but not in Thread, if you use the same
New Thread (MT). Start ();//An instantiation of the object Mt will cause an exception
New Thread (MT). Start ();
}
};
Although the program now has three threads, but sold a total of 10 tickets, that is, the use of runnable implementation of multi-threading can achieve the purpose of resource sharing.
http://blog.csdn.net/wwww1988600/article/details/7309070
The difference between runnable and thread in Java