1. The instance requires the design of A thread operation class, which requires that three thread objects can be generated, and the sleep time of three threads can be set separately: thread A: Sleep for 10 seconds thread B: sleep for 20 seconds Thread C: Sleep for 30 seconds 2. The name attribute exists directly in the Thread class by inheriting the Thread class.
Class MyThread extends Thread {private int time; public MyThread (String name, int time) {super (name); // set the Thread name this. time = time; // set the sleep time} public void run () {try {Thread. sleep (this. time); // time specified for sleep} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (Thread. currentThread (). getName () + "thread, sleep" + this. time + "millisecond. ") ;}}; Public class ExecDemo01 {public static void main (String args []) {MyThread mt1 = new MyThread (" thread A ", 10000 ); // define the thread object and specify the sleep time MyThread mt2 = new MyThread ("thread B", 20000); // define the thread object, specify the sleep time MyThread mt3 = new MyThread ("thread C", 30000); // define the thread object and specify the sleep time mt1.start (); // start the thread mt2.start (); // start the mt3.start () thread; // start the thread }};
3. the Runnable interface should be implemented to add a name attribute to save the thread name.
Class MyThread implements Runnable {private String name; private int time; public MyThread (String name, int time) {this. name = name; // set the thread name this. time = time; // set the sleep time} public void run () {try {Thread. sleep (this. time); // time specified for sleep} catch (InterruptedException e) {e. printStackTrace ();} System. out. println (this. name + "thread, sleep" + this. time + "millisecond. ") ;}}; Public class ExecDemo02 {public static void main (String args []) {MyThread mt1 = new MyThread (" thread A ", 10000 ); // define the thread object and specify the sleep time MyThread mt2 = new MyThread ("thread B", 20000); // define the thread object, specify the sleep time MyThread mt3 = new MyThread ("Thread C", 30000); // define the Thread object and specify the sleep time new Thread (mt1 ). start (); // start the Thread new Thread (mt2 ). start (); // start the Thread new Thread (mt3 ). start (); // start thread }};