Java has two ways to implement multithreading, the first is to inherit the thread class, and the second is to implement the Runnable interface. The connection between them:
1, the thread class implements the Runable interface.
2, all need to rewrite the inside run method.
The difference between them. "
1, the implementation of the Runnable class is more robust, to avoid the limitations of single inheritance.
2, runnable easier to achieve resource sharing, can be multiple threads at the same time processing a resource.
Take a look at the example of selling tickets to inherit thread:
public static void Main (string[] args) {
//TODO auto-generated method stub
New Mythread (). Start ();
New Mythread (). Start ();
Class Mythread extends thread{
private int ticket = 5;
public void Run () {while
(true) {
System.out.println ("Thread ticket =" + ticket--);
if (Ticket < 0) {break
;
}
}
}}
Output results:
Thread ticket = 5
Thread ticket = 5
Thread ticket = 4
Thread ticket = 4
Thread ticket = 3
thread Ticke t = 2
Thread ticket = 3
Thread ticket = 1
Thread ticket = 2
Thread ticket = 0
Thread ticket = 1
t Hread ticket = 0
From the above output can be seen, we created 2 multithreaded objects, they realized the ticket purchase task, that is, a total of 12 tickets sold.
Example of selling tickets to implement Runnable interface:
<pre name= "code" class= "html" >public static void Main (string[) args) {
//TODO auto-generated method stub
mythread2 m=new MyThread2 ();
New Thread (M). Start ();
New Thread (M). Start ();
Class MyThread2 implements runnable{
private int ticket = 5;
public void Run () {while
(true) {
System.out.println ("Runnable ticket =" + ticket--);
if (Ticket < 0) {break
;
}
}
}}
Output results:
Runnable ticket = 5
Runnable ticket = 4
Runnable ticket = 3
Runnable ticket = 2
Runnable ticket = 1
Ru Nnable ticket = 0
From the result we can see that although we have declared two threads, we have sold 6 tickets altogether. They have realized resource sharing. PS: In the actual development, must pay attention to the naming norms, followed by the above implementation of the Runable interface as a result of the operation of a resource, will appear thread unsafe situation, if circumstances require, we need to synchronize operations.