1. How do I create multithreading?
Java implements multi-threading from a language level, so implementing a multithreaded program is easy. There are two ways to implement multi-threading, which is to inherit the thread class and implement the Runnable interface. Because Java does not support multiple inheritance reasons, it is recommended to implement multithreading by implementing the Runnable interface as much as possible.
Using the Runnable interface for multithreading has the following advantages:
1, to avoid the limitations of Java's single inheritance characteristics.
2, enhance the robustness of the program. Code can be shared by multiple threads. The code and the data are independent;
3. Suitable for multiple threads with the same program code to handle the same resource situation.
The difference between the two:
*thread also implements the Runnable interface, so the subclass that inherits from the thread class also implements the Runnable interface
* Inherit the thread class to implement multi-threading, each of which is exclusive to the code in the Run method, and multithreading that implements the Runnable interface collectively owns the data and code in the Run method.
* Inheriting the thread class to implement multi-threading, because the exclusive code all does not thread security issues. Multithreading that is implemented by the Runnable interface is not secure.
A sample is a case where multiple forms sell tickets. Sample and Code citation: http://blog.csdn.net/ns_code/article/details/17161237
To implement multithreaded code by inheriting the thread class:
class MyThread extends Thread{ Private intTicket =5; Public voidRun () { for(intI=0;i<Ten; i++) {if(Ticket >0) {System.out.println ("ticket ="+ ticket--); } } }} Public class threaddemo{ Public Static voidMain (string[] args) {NewMyThread (). Start ();NewMyThread (). Start ();NewMyThread (). Start (); }}
To implement the Runnable interface to implement multithreading code is:
class MyThread implements Runnable{ Private intTicket =5; Public voidRun () { for(intI=0;i<Ten; i++) {if(Ticket >0) {System.out.println ("ticket ="+ ticket--); } } }} Public class runnabledemo{ Public Static voidMain (string[] args) {MyThread my =NewMyThread ();NewThread (My). Start ();NewThread (My). Start ();NewThread (My). Start (); }}
Java multithreaded series-thread creation