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

看板java作者 (達)時間8年前 (2015/07/25 21:35), 編輯推噓0(003)
留言3則, 2人參與, 最新討論串1/2 (看更多)
下面的程式碼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

07/25 21:49, , 1F
因為Thread就是有Thread(Runnable)這個ctor,本來就可以
07/25 21:49, 1F

07/25 21:52, , 2F
Thread的run原本的實作是執行ctor傳進來的Runnable的run
07/25 21:52, 2F

07/26 11:12, , 3F
http://goo.gl/N1RtP Thread的doc
07/26 11:12, 3F
文章代碼(AID): #1Liv2OJd (java)
文章代碼(AID): #1Liv2OJd (java)