[問題] 執行緒方面的問題

看板java作者 (西狂)時間11年前 (2014/01/16 22:57), 編輯推噓3(308)
留言11則, 5人參與, 最新討論串1/2 (看更多)
public interface Runnable { public abstract void run(); } class FatherThread implements Runnable { public void run() { System.out.println("爸爸下班回家."); System.out.println("爸爸準備洗澡."); System.out.println("爸爸發現沒瓦斯了."); System.out.println("爸爸打電話請瓦斯工人送瓦斯."); Thread worker = new Thread(new WorkerThread()); System.out.println("爸爸等待瓦斯工人..."); worker.start(); try { worker.join(); } catch(InterruptedException e) { System.out.println("爸爸決定今天不洗熱水澡了 !"); } System.out.println("爸爸開始洗澡 !"); System.out.println("爸爸洗完澡了 !"); } } class WorkerThread implements Runnable { public void run() { System.out.println(); System.out.println("瓦斯工人送瓦斯中..."); try { for(int i=1; i<=5; i++) { Thread.sleep(1000); System.out.print(i + " 分鐘, "); } } catch(InterruptedException ie) { System.err.println("瓦斯工人送瓦斯途中發生意外 !"); } System.out.println(); System.out.println("瓦斯工人將瓦斯送到家了 !"); System.out.println("瓦斯工人將瓦斯安裝完畢 !"); System.out.println(); } } public class Shower { public static void main(String[] args) { Thread father = new Thread(new FatherThread()); father.start(); } } 我剛才實作了這個範例,用 FatherThread 及 WorkerThread implements Runnable 的 介面,可是在 FatherThread 中的其中一行 Thread worker = new Thread(new WorkerThread()); 及主程式 Shower 的其中一行 Thread father = new Thread(new FatherThread()); 的等號右邊均出現了 The constructor Thread(WorkerThread/FatherThread) is undefined 這個問題,請問一下為什麼會這樣?且我若將 FatherThread 及 WorkerThread 的 implements Runnable 改成 extends Thread 就又可以解決了,這又是什麼原因呢 ?懇請板上的眾高手幫忙解除我的疑惑,感激不盡 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 1.171.161.156

01/16 23:08, , 1F
==" 就 API 規格就是這樣開... 在搞 thread 之前先
01/16 23:08, 1F

01/16 23:08, , 2F
弄好基礎吧.... Orz
01/16 23:08, 2F

01/16 23:12, , 3F
歹勢,小弟是新手^^",請問API規格是指?
01/16 23:12, 3F

01/16 23:16, , 4F
我記得介面可以多重繼承啊
01/16 23:16, 4F

01/17 08:20, , 5F
你是不是自己寫兩個檔案 一個是Runnable 一個是Shower?
01/17 08:20, 5F

01/17 09:22, , 6F
你不需要自己寫Runnable interface..
01/17 09:22, 6F

01/17 13:38, , 7F
不只是不需要 是不能自己寫啊www
01/17 13:38, 7F

01/17 15:11, , 8F
回c大:是,Runnable是介面,Shower是主程式
01/17 15:11, 8F

01/17 20:04, , 9F
樓上已經給你答案 因為Thread的Constructor是接受
01/17 20:04, 9F

01/17 20:05, , 10F
java.lang.Runnable而非你自訂的Runnable
01/17 20:05, 10F

01/17 20:35, , 11F
我了解了,把Runnable移除掉就沒問題了,謝謝大家
01/17 20:35, 11F
文章代碼(AID): #1Ir_DX6f (java)
討論串 (同標題文章)
文章代碼(AID): #1Ir_DX6f (java)