实现Runnable接口的类必须使用Thread类的实例才能创建线程。通过Runnable接口创建线程分为两步:
1. 将实现Runnable接口的类实例化。
2. 建立一个Thread对象,并将第一步实例化后的对象作为参数传入Thread类的构造方法。
最后通过Thread类的start方法建立线程。
1 package com.fly.example; 2 3 public class MyRunnableThree implements Runnable { 4 5 @Override 6 public void run() 7 { 8 System.out.println(Thread.currentThread().getName()); 9 } 10 public static void main(String[] args) 11 { 12 MyRunnableThree t1 = new MyRunnableThree(); 13 MyRunnableThree t2 = new MyRunnableThree(); 14 MyRunnableThree t3 = new MyRunnableThree(); 15 Thread thread1 = new Thread(t1, "MyThread1"); 16 Thread thread2 = new Thread(t2); 17 Thread thread3 = new Thread(t3); 18 thread2.setName("MyThread2"); 19 thread1.start(); 20 thread2.start(); 21 thread3.start(); 22 23 } 24 25 }
运行结果如下:
MyThread1
MyThread2
Thread-1