package cm; public class test20180503RunableInterfaces implements Runnable { public static void main(String[] args) { Thread a = new Thread(new test20180503RunableInterfaces(), "test20180503RunableInterfaces");// Thread构造器接受两个参数,第一个参数为实现了runnable接口的类,第二个参数为线程名。 a.setDaemon(true);// 这里设置成守护线程,结果是还没打印线程名,此线程就已经结束了,这是一个不恰当的做法。 a.start();//启动a线程,start()方法进行必要的初始化,并调用run()方法。 } public String toString() { return Thread.currentThread().getName();//返回当前线程的名称:test20180503RunableInterfaces } @Override public void run() { while (true) { System.out.println(this); try { Thread.currentThread().sleep(1000);//使当前线程睡眠1秒钟 } catch (InterruptedException e) { e.printStackTrace(); } } } }
为什么可以继承Thread类创建线程,还需要Runnable接口呢?这样是为了提供给更好的灵活性,有时你可能想要只是创建一个线程,但不想为你当前类,添加过多的Thread中的东西。所以使用Runnable。其实就是类只能从一个类中继承,但是可以实现多个接口!!!!!!!!!!!