Thread and process relationships: one process has n threads
1. Three ways to implement threads:
(1) Inherit the thread class
[1] Creating a class that inherits the thread class
Package Thread01; Public class extends Thread { privateint i; @Override publicvoid run () { for (; i <; i++ ) { C18/>system.out.println (GetName ()+ "\ t" +i) ; }}}
[2] Creating a test class
PackageThread01; Public classMyTest { Public Static voidMain (string[] args) { for(inti = 0; I <10; i++) {System.out.println (Thread.CurrentThread (). GetName ()+ "\ T" +i+ "======"); if(i==5) {MyThread mt2=NewMyThread (); MyThread MT=NewMyThread (); Mt2.start (); Mt.start (); } } } Public Static Longgetmemory () {returnruntime.getruntime (). Freememory (); }}
(2) Implement Runnable interface
The class "1" Implements the Runnable interface is not a thread class, but a target of a thread class that can provide parameters for thread class construction methods to enable thread opening
PackageThread02; Public classSecondthreadImplementsrunnable{Private inti; Public voidrun () { for(; i <; i++) {System.out.println (Thread.CurrentThread (). GetName ()+" "+i); if(i==20) {System.out.println (Thread.CurrentThread (). GetName ()+ "Execution Complete"); } } }}
"2" Test class
PackageThread02; Public classMyTest { Public Static voidMain (string[] args) { for(inti = 0; I < 10; i++) {System.out.println (Thread.CurrentThread (). GetName ()+" "+i); if(i==5) {secondthread S1=NewSecondthread (); Thread T1=NewThread (S1, "Thread 1")); Thread T2=NewThread (S1, "Thread 2")); T1.start (); T2.start (); } } }}
(3) Implement callable interface
"1" Create callable implementation class
Package Thread03; Import java.util.concurrent.Callable; Public class Implements Callable<integer> { int i=0; Public throws Exception { for (; i <; i++ ) { System.out.println (Thread.CurrentThread ()). GetName ()+ "" +i); } return i; }}
"2" Test class
PackageThread03;ImportJava.util.concurrent.FutureTask; Public classThirdthread { Public Static voidMain (string[] args) {Target T1=NewTarget (); Futuretask<Integer> ft=NewFuturetask<integer>(t1); Thread T2=NewThread (FT, "new Thread"); T2.start (); Try{System.out.println (Ft.get ()); } Catch(Exception e) {//Todo:handle Exception } }}
3 Ways to start threads