2013-09-21 106 views
1

當我通過t.start()調用run(),但通過obj.start()得不到相同的輸出時,我正在輸出輸出。可能是什麼原因?爲什麼start()在我的擴展線程中不起作用

任何人都可以解釋這一點嗎?

class Ex1 implements Runnable { 

    int n; 
    String s; 

    public void run(){ 
     for(int i=1;i<=n;i++){ 
      System.out.println(s +"-->"+ i); 
     } 
    } 
} 


class RunnableDemo extends Thread { 

    Ex1 e; 
    RunnableDemo(Ex1 e) { 
     this.e = e; 
    } 

    public static void main(String[] args) {  

     Ex1 obj1 = new Ex1(); 
     Ex1 obj2 = new Ex1(); 

     obj1.n = 5; 
     obj1.s = "abc"; 

     // Thread t = new Thread(obj1); 
     // t.start(); 
     RunnableDemo obj = new RunnableDemo(obj1); 
     obj.start(); 
    } 
} 

回答

4

我相信你需要調用super在RunnableDemo的構造函數:

RunnableDemo(Ex1 e){ 
     super(obj); 
     this.e = e; 
} 

這將調用父類的(Thread)構造與obj參數,以便啓動方法按預期工作。

沒有這樣做,你實際上隱式調用super而沒有參數,因此沒有爲RunnableDemo實例設置runnable。

0

您還需要添加@Overriderun()

@Override 
public void run(){ 
    for(int i=1;i<=n;i++){ 
     System.out.println(s +"-->"+ i); 
    } 
} 
0

的問題是,使得Thread一個子類,當你沒有覆蓋run方法。由於默認的run方法沒有做任何事情,您不會得到任何結果。

相關問題