1. Inheriting the thread class
Source:
PackageCom.zy.test.www.multiThread;/*** Multithreading Implementation Method 1: Inherit the thread class *@authorZy*/ Public classByextendsthreadextendsthread{ PublicByextendsthread (String name) {Super(name); } @Override Public voidrun () {System.out.println (GetName ()+ "thread run start!"); for(inti = 1; I <= 5; i++) {System.out.println (GetName ()+ " " +i); Try{sleep (int) Math.random () * 10); } Catch(interruptedexception e) {e.printstacktrace (); }} System.out.println (GetName ()+ "Thread run end!"); } Public Static voidMain (string[] args) {System.out.println (Thread.CurrentThread (). GetName ()+ "thread run start!"); NewByextendsthread ("A"). Start (); NewByextendsthread ("B"). Start ();System.out.println (Thread.CurrentThread (). GetName ()+ "Thread run end!"); }}
Operating effect:
Main thread run start!
A thread runs to start!
Main thread run end!
A 1
B thread Run start!
B 1
A 2
B 2
A 3
B 3
A 4
B 4
A 5
B 5
A thread runs the end!
B Thread Run end!
2. Implement the Runnable interface
Source:
PackageCom.zy.test.www.multiThread;/*** Multithreading Implementation Mode 2: Implement Runnable interface *@authorZy*/ Public classByimplementsrunnableImplementsrunnable{@Override Public voidrun () {System.out.println (Thread.CurrentThread (). GetName ( )+ "thread run start!"); for(inti = 1; I <= 5; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ " " +i); Try{Thread.Sleep (int) Math.random () * 10); } Catch(interruptedexception e) {e.printstacktrace (); }} System.out.println (Thread.CurrentThread (). GetName ()+ "Thread run end!"); } Public Static voidMain (string[] args) {System.out.println (Thread.CurrentThread (). GetName ()+ "thread run start!"); Byimplementsrunnable byimplementsrunnable=Newbyimplementsrunnable (); NewThread (byimplementsrunnable, "A"). Start (); NewThread (byimplementsrunnable, "B"). Start (); System.out.println (Thread.CurrentThread (). GetName ()+ "Thread run end!");
}}
Operating Effect:
Main thread run start! A thread runs to start ! main thread run end ! 1B thread run start ! 122334455A thread run end ! B thread run end !
How to implement multithreading common in 3