How to get an object inside an object?

I'm trying to use thread, can someone tell me what is wrong in the following code. I get NullPointerExceptionmostly.

 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();
  }
}
+3
source share
4 answers

In your constructor, you declare a local variable with a name tthat uses the same name as your field t. Just replace Thread twith this.tor just tthere:

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

BTW1, it is strongly recommended that you start class names with capital letters, i.e. ThreadTestin your case would be a better name.

BTW2 worthy of an IDE will detect this error for you and draw your attention to it.

+5
source

Thread t , threadtest Runnable.

t new Thead(threadtest).start(); java.util.concurrent.Executors.newSingleThreadExecutor().submit(threadtest);

0

You must pass "this" to the constructor of your thread if you want your own runnable to be executed.

0
source

Hey there! in fact, Grzegorz Oledsky largely has the correct answer, but there is one more thing that was missed - in your constructor you still need to pass thisThread as the parameter. because right now you have runnable, but just pass the string nameto the Thread constructor. it won’t do anything.

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

Source: https://habr.com/ru/post/1787948/


All Articles