There are two ways to implement multithreading in Java: To inherit the thread class and implement the Runnable interface, as long as it is multi-threaded in the development of the program, it is always to realize the runnable interface, because the implementation of the Runnable interface has the following advantages over the inheritance thread class:
1, can avoid the single inheritance of Java because of the limitations caused by the characteristics;
2, enhance the robustness of the program, code can be shared by multiple threads, the code and data is independent;
3. A thread area that is suitable for multiple identical program codes handles the same resource.
The following is an example of a typical ticket-buying process (basically taking this as an example) to illustrate the difference.
The code is implemented first by inheriting the thread class:
[Java] View plain copy class mythread extends thread{ private int ticket = 5; public void run () { for (int i=0;i<10;i++) { if (ticket > 0) { system.out.println ("ticket = " + ticket--) ; } } } } public class threaddemo{ public static void Main (string[) args) { new mythread (). Start (); new mythread (). Start (); new mythread (). Start (); } } The results of a certain implementation are as follows:
As can be seen from the results, each thread sold a separate 5 tickets, that is, the independent completion of the task of buying tickets, but the actual application, such as the railway station ticketing, need multiple threads to work together to complete the task, in this case, that is, multiple threads to buy 5 tickets together.
The following is a multithreaded program implemented through the implementation of the Runnable interface, with the following code:
[Java] View plain copy class mythread implements runnable{ private int ticket = 5; public void run () { for (int i=0;i<10;i++) { if (ticket > 0) { system.out.println ("ticket = " + ticket--); } } } } public class runnabledemo{ public static void main (STring[] args) { MyThread my = New mythread (); new thread (My). Start (); new thread (My). Start ();