I wonder if every time I create an object in java it initializes a Thread

Asked

Viewed 74 times

3

I have a class that extends the Thread class, wanted to know if every time I create an object it initializes a Thread.

class Objeto{

      String nomeObjeto;

      public Objeto(String nomeObjeto){
          this.nomeObjeto = nomeObjeto;
      }

      public static void main(String[] args){
          new Objeto().start();//Objeto 1
          new Objeto().start();//Objeto 2
      }

}
  • Ahh, I forgot something in the code, this class extends the Thread class

  • 5

    Only create object does not start to Thread you will need to call the method Start() as in the code you posted: new Objeto().start()

2 answers

2

Your code is probably not complete because your class Objeto has no method start().

If what’s missing is the extends Thread, then, yes, by putting this, two threads will be created (one in each call of start()). This can be verified in official documentation.

If what is missing is the definition of start(), this being some method created by you, so, no, threads will not be created.

1


The most basic way to create a thread (thread) in Java is creating a new instance of the 'Thread' class and calling the 'start()' method, after which the 'run()' method of the instance will be run in the other thread.

The 'run()' method of the 'Thread' class does not perform anything, so we usually extend the class and override the method. Another alternative is to create a class that implements the 'Runnable' interface and pass an instance of that class in the constructor of the 'Thread' class'.

Anyway, when creating an instance of 'Thread' or a subclass you will potentially have a new thread, but will only run when you start().

Each new instance you run is a new one thread and only one, since threads cannot be reused, that is, executed more than once.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.