2011-01-26 234 views
3

我想使用線程誰能告訴我什麼是在下面的代碼中的錯誤。我主要獲得NullPointerException如何獲取對象內的對象?

public class threadtest implements Runnable { 

    Thread t; 

    public threadtest(String name) { 
    Thread t = new Thread(name); 
    } 

    public void run() { 
    for(int i = 0; i <= 10; i++) { 
     try { 
     Thread.sleep(1000); 
     } 
     catch(Exception e) { 
     System.out.println(e); 
     } 
    } 
    } 

    public static void main(String args[]) { 
    threadtest ob = new threadtest("satheesh"); 
    ob.t.start(); 
    } 
} 
+0

錯誤的是代碼的格式。 – Istao 2011-01-26 13:04:38

回答

5

在構造函數聲明稱爲t一個局部變量,它使用相同的名稱字段t。只需用this.t或簡單t有取代Thread t

public threadtest(String name) { 
    this.t=new Thread(name); 
} 

BTW1,強烈建議用大寫字母開始的類名,即ThreadTest你的情況會是一個更好的名字。

BTW2,一個體面的IDE會發現你的錯誤,並提請你注意這一點。

0

字段Thread t從不使用,threadtest本身是一個Runnable。

刪除t,並調用new Thead(threadtest).start();java.util.concurrent.Executors.newSingleThreadExecutor().submit(threadtest);

0

你必須通過「本」到你的線程的構造函數,如果你想你自己的可運行得到執行。

0

嘿!實際上,Grzegorz Oledzki幾乎都有正確的答案,但是,還有一件事被忽略了 - 你的構造函數中有 ,你仍然需要將this作爲參數傳遞給Thread。因爲現在,你實現了runnable,但只是將字符串name傳遞給Thread構造函數。那什麼都不會做。

public threadtest(String name) { 
    t = new Thread(this, name); 
}