第一种方式,继承Thread类
1 public class Thread extends java.lang.Thread { 2 3 private String name; 4 5 // 定义run方法 6 public void run() { 7 for (int i = 0; i < 20; i++) { 8 System.out.println(name + "haha"); 9 } 10 } 11 12 // 构造函数重写构(无参) 13 public Thread() { 14 15 } 16 17 // 有参数的构造函数 18 public Thread(String name) { 19 20 this.name = name; 21 } 22 23 public static void main(String[] args) { 24 25 Thread t1 = new Thread("T1"); 26 Thread t2 = new Thread("T2"); 27 28 t1.start(); 29 t2.start(); 30 31 } 32 33 }
运行结果
1 T1haha 2 T1haha 3 T1haha 4 T1haha 5 T1haha 6 T2haha 7 T2haha 8 T2haha 9 T2haha 10 T2haha 11 T2haha 12 T2haha 13 T2haha 14 T2haha 15 T2haha 16 T2haha 17 T2haha 18 T2haha 19 T2haha 20 T2haha 21 T2haha 22 T2haha 23 T2haha 24 T2haha 25 T2haha 26 T1haha 27 T1haha 28 T1haha 29 T1haha 这种方式继承Thread类,直接通过Thread开启,这个run方法只是线程开启类内部自己调用,并不是用线程调用的也就是说线程的开启并不是Thread.run() 第二种方式实现Runnable 接口,实现这个接口会自动重写run方法
1 public class Hello implements Runnable { 2 3 private String name; 4 5 // 定义run方法 6 public void run() { 7 for (int i = 0; i < 20; i++) { 8 System.out.println(name + "haha"); 9 } 10 } 11 12 // 构造函数重写构(无参) 13 public Hello() { 14 15 } 16 17 // 有参数的构造函数 18 public Hello(String name) { 19 20 this.name = name; 21 } 22 23 public static void main(String[] args) { 24 25 Hello h1 = new Hello("h1"); 26 Thread t1 = new Thread(h1); 27 Hello h2 = new Hello("h2"); 28 Thread t2 = new Thread(h2); 29 t1.start(); 30 t2.start(); 31 32 } 33 34 }
运行结果
1 h2haha 2 h1haha 3 h2haha 4 h1haha 5 h2haha 6 h1haha 7 h2haha 8 h1haha 9 h2haha 10 h1haha 11 h2haha 12 h1haha 13 h2haha 14 h1haha 15 h2haha 16 h1haha 17 h2haha 18 h1haha 19 h2haha 20 h1haha 21 h2haha 22 h1haha 23 h2haha 24 h1haha 25 h2haha 26 h1haha 27 h2haha 28 h1haha 29 h2haha 30 h1haha 31 h2haha 32 h1haha 33 h2haha 34 h1haha 35 h2haha 36 h1haha 37 h2haha 38 h1haha 39 h2haha 40 h1haha
这种方式也开启成功
总结:这两种方式都可以开启线程,区别是,一个实现接口,一个继承Thread类,一般都去实现接口,有两点好处:1,实现接口的run方法类可以帮你构造出来 2,Java支持单继承,但可以实现多个接口。个人想法:Thread类就好比是一个载体,都可以用,继承Thread就是直接使用,而runnable接口就相当于在中间过渡一下,得自己创建类对象(这个类对象实现runnable接口),然后放到Thread载体上,Thread就可以自动调用run方法。(总结纯属个人观点)
时间: 2024-10-13 17:27:08