There are 2 ways to implement multithreading in Java:
1. Inherit thread
Public classThreaddemoextendsThread {String name; Private intCount = 100; //using the parameter constructor of the thread classThreaddemo (String name) { This. Name =name; } Public voidrun () {//compute primes larger than minprime for(inti = 0; I < 100; i++) {calccount (); System.out.println ("Thread Start:" + This. Name + ", i=" + i + ", count=" +count); } //System.out.println (name); } Private synchronized voidCalccount () {if(Count > 0) {Count--; } } Public Static voidMain (string[] args) {Threaddemo TD=NewThreaddemo ("1"); Threaddemo TD2=NewThreaddemo ("2"); Threaddemo TD3=NewThreaddemo ("3"); Td.start (); Td2.start (); Td3.start (); }}
2. Implement the Runnable interface
Public classRunnabledemoImplementsrunnable{String name; Runnabledemo (String name) { This. name=name;} @Override Public voidrun () {//TODO auto-generated Method Stub for(inti=0;i<100;i++) {System.out.println ("Thread Start:" + This. name+ ", i=" +i); } } Public Static voidMain (string[] args) {Runnabledemo rd=NewRunnabledemo ("1"); Runnabledemo Rd2=NewRunnabledemo ("2"); Runnabledemo Rd3=NewRunnabledemo ("3"); NewThread (Rd, "WW"). Start (); NewThread (Rd2). Start (); NewThread (Rd3). Start (); }}
Both of these methods can be done in a normal multi-threaded processing, online: The general use of multithreading is to implement the Runnable interface with the business class.
Look at the definition of thread:
public class Thread implements runnable{...}
We know that thread is actually the official implementation of runnable in Java, if we don't need special control, we can use thread directly.
The situation is a bit like the implementation of the list, we use ArrayList in Java, of course, you can also customize a list of the implementation of the class to come out ....
Resource synchronization
The use of multithreading will have to mention thread synchronization, in order to access limited resources, locking the resources is a necessary operational steps. Of course, locking is also a matter of consuming system resources, need to make some trade-offs in development.
Commonly used locking methods have synchronized, lock, can be simply considered as the difference between automation and manual processing.
More of the synchronous talk is: http://www.cnblogs.com/devinzhang/archive/2011/12/14/2287675.html
Java Multithreading Implementation