这种方式是把一个实现了Runnable接口的类的实例作为target来创建Thread。
public class SecondThread implements Runnable { private int i; @Override public void run() { for (; i < 100; i++) { System.out.println(Thread.currentThread().getName() + " " + i); } } public static void main(String[] args) { for (int i = 0; i < 100; i++) { System.out.println(Thread.currentThread().getName() + " " + i); if (i == 20) { SecondThread st = new SecondThread(); new Thread(st, "new Thread1").start(); new Thread(st, "new Thread2").start(); } } } }
从以上代码可以发现,通过继承Thread类创建的线程要获取当前线程直接使用this就可以,而通过实现Runnable接口来获得当前线程需要使用Thread.currentThread()来获取当前线程对象。运行上列代码可以发现,上述两个Thread是通过Runnable实现类的同一个对象st作为target来创建的,它们共享同一个实例成员变量i,因此两个线程的循环数字是连续的。