1. Inheriting the thread class
The thread class is a concrete class, not an abstract class.
PackageSe.thread;Importjava.util.Date; Public classThreadTestextendsThread { Public intTime ; PublicString name; ThreadTest (inttime,string name) { This. name=name; This. time=Time ; } Public voidrun () { while(true){ Try{System.out.println ("User" + This. name+ "is resting, time:" +NewDate ()); Thread.Sleep ( This. Time); } Catch(interruptedexception e) {e.printstacktrace (); } } } Public Static voidMain (string[] args) {threadtest threadTest1=NewThreadTest, "Jack"); Threadtest1.start (); ThreadTest ThreadTest2=NewThreadTest ("Lolo"); Threadtest2.start (); }}
2. Implement the Runable interface
PackageSe.thread;Importjava.util.Date; Public classTreadTest2ImplementsRunnable { Public intTime ; PublicString name; PublicTreadTest2 (inttime,string name) { This. name=name; This. time=Time ; } @Override Public voidrun () { while(true){ Try{System.out.println ("User" + This. name+ "is resting, time:" +NewDate ()); Thread.Sleep ( This. Time); } Catch(interruptedexception e) {e.printstacktrace (); } } } Public Static voidMain (string[] args) {TreadTest2 threadTest2=NewTREADTEST2 (3000, "004"); TreadTest2 treadTest22=NewTreadTest2 (2000, "125"); NewThread (ThreadTest2). Start (); NewThread (treadTest22). Start (); }}
3. Select the thread class or the Runable interface?
1. If you just want to rewrite the runable interface instead of overriding the thread other methods, use the Runable interface.
2. If a subclass inherits other non-thread classes, it can only implement the override of run () by implementing the Runable interface.
Java core programming-thread threading Development Method (II)