Multithreading
The difference between threads and processes
Creating Threads
- By implementing the Runnable interface
1 classRunnabledemoImplementsrunnable{2 PrivateThread t; Create a thread3 PrivateString ThreadName;4 5 Runnabledemo (String name) {6ThreadName =name;7System.out.println ("Creating" +threadname);8 Try{9 for(inti = 3; i > 0; i--){TenSystem.out.println ("Thread:" + ThreadName + "," +i); One //wait for a while. AThread.Sleep (50); - } -}Catch(interruptedexception e) { theSystem.out.println ("Thread" + threadname + "interrupted"); - } -System.out.println ("Thread" + ThreadName + "exiting."); - } + - + Public voidstart () { ASystem.out.println ("starting" + threadname); at if(T = =NULL){ -t =NewThread ( This, threadname); - T.start (); - } - } - in Public classtestthread{ - Public Static voidMain (string[] args) { toRunnabledemo R1 =NewRunnabledemo ("Thread-1"); + R1.start (); - theRunnabledemo R2 =NewRunnabledemo ("Thread-2"); * R2.start (); $ }Panax Notoginseng}
When an object implementing interface Runnable was used to create a thread, starting the thread causes the object ' s run meth Od to is called in that separately executing thread.
- By inheriting the thread class
classThreaddemoextendsThread {PrivateThread t; PrivateString ThreadName; Threaddemo (String name) {ThreadName=name; System.out.println ("Creating" +threadname); } Public voidrun () {System.out.println ("Running" +threadname); Try { for(inti = 4; i > 0; i--) {System.out.println ("Thread:" + ThreadName + "," +i); //Let the thread sleep for a while.Thread.Sleep (50); } }Catch(interruptedexception e) {System.out.println ("Thread" + ThreadName + "interrupted."); } System.out.println ("Thread" + ThreadName + "exiting."); } Public voidstart () {System.out.println ("Starting" +threadname); if(T = =NULL) {T=NewThread ( This, ThreadName); T.start (); } }} Public classTestthread { Public Static voidMain (String args[]) {Threaddemo T1=NewThreaddemo ("Thread-1"); T1.start (); Threaddemo T2=NewThreaddemo ("Thread-2"); T2.start (); } }
Java.lang.Thread
public class Threadextends Objectimplements Runnable
Lock
Synchronous
Reference:
Http://www.tutorialspoint.com/java/java_multithreading.htm
Http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html
Https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
Java multi-Threading and locking