[問題] 不用extends Thread即可new出Thread物件

作者: dharma (達)   2015-07-25 21:35:18
下面的程式碼A要先extends Thread
才能做:TimerThread newThread = new TimerThread();
為什麼程式碼B沒有extends Thread之類的動作
就能使用Thread:Thread newThread = new Thread(test)
為什麼呢
thanks
程式碼A:
class TimerThread extends Thread { //執行緒
public void run() { // 執行緒要執行的內容
...
}
}
public class TestThread {
public static void main(String[] argv) {
TimerThread newThread = new TimerThread();
newThread.start(); // 啟動執行緒
...
}
}
程式碼B:
class TimerThread implements Runnable {//以Runnable介面建立執行緒
public void run() { // 執行緒要執行的內容
...
}
}
public class TestRunnable {
public static void main(String[] argv) {
TimerThread test = new TimerThread();
Thread newThread = new Thread(test)
newThread.start(); // 啟動執行緒
...
}
}
作者: ssccg (23)   2015-07-25 21:49:00
因為Thread就是有Thread(Runnable)這個ctor,本來就可以Thread的run原本的實作是執行ctor傳進來的Runnable的run
作者: MonyemLi (life)   2015-07-26 11:12:00
http://goo.gl/N1RtP Thread的doc

Links booklink

Contact Us: admin [ a t ] ucptt.com