如何在对象中获取对象?

sat*_*oid 3 java

我试图使用线程可以任何人告诉我在下面的代码中有什么问题.我得到一个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();
  }
}
Run Code Online (Sandbox Code Playgroud)

Grz*_*zki 5

在构造函数中,声明一个名为local的变量t,该变量使用与您的字段相同的名称t.只需更换Thread t用this.t或简单的t有:

public threadtest(String name) {
  this.t=new Thread(name);
}
Run Code Online (Sandbox Code Playgroud)

BTW1,强烈建议用大写字母开始课程名称,即ThreadTest在你的情况下是一个更好的名字.

BTW2,一个不错的IDE会为你发现这个错误,并引起你的注意.