1 /** 2 3 * 创建一个子线程, 完成1-100之间自然数的输出,同样的主线程执行同样的操作 4 5 *创建多线程的第二种方式,通过实现的方式 6 7 * 继承和实现的方式对比 8 9 * 一,联系: 10 11 * public class Thread extends Object implements Runnable 12 13 * 二,两个方式好,实现的方式好 14 15 * why?实现的方式避免了Java单继承的局限性,如果多个线程要操作一份数据,更适合使用实现的方式 16 17 */ 18 19 //1创建一个实现了Runnable接口类 20 21 class PrintNum1 implements Runnable{ 22 23 //2实现接口的抽象方法 24 25 public void run(){ 26 27 for(int i = 1;i<101;i++){ 28 29 System.out.println(Thread.currentThread().getName()+":"+i); 30 31 } 32 33 } 34 35 } 36 37 38 39 public class TestThread2 { 40 41 42 43 public static void main(String[] args) { 44 45 //3创建一个Runnable接口实现类的对象 46 47 PrintNum1 pn = new PrintNum1(); 48 49 //要想启动一个多线程,必须调用start 50 51 //4将实现类对象作为形参传递给Thread类的构造器中,创建Thread类的对象,此对象即为一个线程 52 53 Thread t1 = new Thread(pn); 54 55 //启动线程,执行Thread对象生成时构造器形参的对象 56 57 //5调动start,启动线程执行run方法 58 59 t1.start(); 60 61 //再创建一个线程 62 63 Thread t2 = new Thread(pn); 64 65 t2.start(); 66 67 } 68 69 }