I wanted to know if each time I create an object in java it initializes a Thread

3

I have a class that extends the Thread class, wanted to know if each 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
      }

}
    
asked by anonymous 26.12.2015 / 11:40

2 answers

1

The most basic way to create a thread in Java is to create a new instance of the Thread class and call the start method. 'run' method of the instance will run on the other thread .

The 'run' method of the 'Thread' class does not execute anything, so in general we 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 into the constructor of the 'Thread' class.

Finally, when creating a Thread instance or a subclass you will potentially have a new thread , but will only execute when you give 'start ()' to it.

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

    
28.12.2015 / 04:18
2

Your code is probably not complete because your Objeto class does not have a start() method.

If what is missing is extends Thread , then, yes, when you put this in, two threads will be created (one in each start() call). This can be verified in official documentation .

If what is missing is the definition of start() , this being any method you have created, then no, no threads will be created.

    
26.12.2015 / 22:50