作者dharma (達)
看板java
標題[問題] 不用extends Thread即可new出Thread物件
時間Sat Jul 25 21:35:18 2015
下面的程式碼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(); // 啟動執行緒
...
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 210.65.89.53
※ 文章網址: https://www.ptt.cc/bbs/java/M.1437831320.A.4E7.html
→ ssccg: 因為Thread就是有Thread(Runnable)這個ctor,本來就可以 07/25 21:49
→ ssccg: Thread的run原本的實作是執行ctor傳進來的Runnable的run 07/25 21:52