Is it possible to reuse a Thread?

1

A Thread dies when its run () method ends. My question is: Does the thread die mean that the Thread object becomes null?

Is it possible to reuse a thread?

    
asked by Missionary robot Robot 21.11.2018 в 21:31
source

2 answers

4

We will solve the doubts one by one.

First, clarify about this:

  

A Thread dies when its run () method ends

An instance of the class Thread represents , within the programming language, to an thread . But the thread of execution as such is not typical of the programming language, but is an artifact of the operating system.

It is the operating system that gives life to the thread and takes care of executing it .

The java%% co class encapsulates what is necessary to manage this device at a low level with the operating system. When the Thread method ends, that execution thread dies in the operating system, and there's nothing to be done about it. It just ended.

  

Does the fact that the thread dies mean that the Thread object becomes null?

No. If you have saved a reference to the instance of run() , it will still have value until you manually assign Thread or exit context.

  

Is it possible to reuse a thread?

In the operating system, it is not. An instance of null created in java, either.

However, in java, as well as in other high-level languages, there are abstractions that allow us to have one or more execution threads and created in the operating system and assign them different jobs. This, to avoid the time involved in creating and terminating threads and optimizing processes. These threads we could say that they are re-usable, although technically speaking they only start and end once, but the abstraction allows us to assign tasks that can start and end several times during his life.

These abstractions are known in English as thread pools . In java, you could search the term in google to inform you. I found this link in a quick search (in English):

Introduction to Thread pools in java

    
answered by 21.11.2018 / 23:18
source
1

A Thread ends when the run() method ends.

Once the variable Thread is finished it does not automatically remain in null , but also can not be used again since it will show java.lang.IllegalThreadStateException .

You can use isAlive() to know if you are still running.

    
answered by 21.11.2018 в 21:45