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。其實就是類只能從一個類中繼承,但是可以實現多個接口!!!!!!!!!!!