1. How do I create multithreading?
Java implements multi-threading from a language level, so implementing a multithreaded applet is straightforward. 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 as much as possible by implementing the Runnable interface. Using the Runnable interface for multithreading has the following advantages:
1, can avoid the Java single inheritance characteristics brought about by the limitations;
2, enhance the robustness of the program, code can be shared by multiple threads, code and data is 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 of the code in the Run method, while the multithreading implemented by the Runnable interface has the data and code in the Run method.
* Inheriting the thread class to implement multi-threading, because the exclusive code all does not have the thread security problem, the Runnable interface implementation of multithreading is not secure.
For example, example and code quoted for selling tickets in multiple windows: 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