Java core programming-thread development method (2), java Development Method
1. inherit the Thread class
The Thread class is a specific class, not an abstract class.
Package se. thread; import java. util. date; public class ThreadTest extends Thread {public int time; public String name; ThreadTest (int time, String name) {this. name = name; this. time = time;} public void run () {while (true) {try {System. out. println ("user" + this. name + "resting, time:" + new Date (); Thread. sleep (this. time);} catch (InterruptedException e) {e. printStackTrace () ;}} public static void main (String [] args) {ThreadTest threadTest1 = new ThreadTest (100, "jack"); threadTest1.start (); threadTest threadTest2 = new ThreadTest (200, "lolo"); threadTest2.start ();}}
2. Implement the Runable Interface
Package se. thread; import java. util. date; public class TreadTest2 implements Runnable {public int time; public String name; public TreadTest2 (int time, String name) {this. name = name; this. time = time ;}@ Override public void run () {while (true) {try {System. out. println ("user" + this. name + "resting, time:" + new Date (); Thread. sleep (this. time);} catch (InterruptedException e) {e. printStackTrace () ;}} public static void main (String [] args) {TreadTest2 threadTest2 = new TreadTest2 (3000, "004"); TreadTest2 treadTest22 = new TreadTest2 (2000, "125"); new Thread (threadTest2 ). start (); new Thread (treadTest22 ). start ();}}
3. Select the Thread class or Runable interface?
1. If you only want to rewrite the Runable interface rather than other methods of Thread, use the Runable interface.
2. If the subclass inherits other non-Thread classes, you can only rewrite run () by implementing the Runable interface.