作者westinsane (西狂)
看板java
標題[問題] 執行緒方面的問題
時間Thu Jan 16 22:57:33 2014
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
推 PsMonkey:==" 就 API 規格就是這樣開... 在搞 thread 之前先 01/16 23:08
→ PsMonkey:弄好基礎吧.... Orz 01/16 23:08
→ westinsane:歹勢,小弟是新手^^",請問API規格是指? 01/16 23:12
→ westinsane:我記得介面可以多重繼承啊 01/16 23:16
推 chunhsiang:你是不是自己寫兩個檔案 一個是Runnable 一個是Shower? 01/17 08:20
推 popcorny:你不需要自己寫Runnable interface.. 01/17 09:22
→ danny8376:不只是不需要 是不能自己寫啊www 01/17 13:38
→ westinsane:回c大:是,Runnable是介面,Shower是主程式 01/17 15:11
→ chunhsiang:樓上已經給你答案 因為Thread的Constructor是接受 01/17 20:04
→ chunhsiang:java.lang.Runnable而非你自訂的Runnable 01/17 20:05
→ westinsane:我了解了,把Runnable移除掉就沒問題了,謝謝大家 01/17 20:35