There is a cycle in which a separate thread is launched for each id of the product id_product :

 for(Int i=0; i<10; i++) { ThreadTest obj_Test = new ThreadTest(); obj_Test.run(id_product); } 

It turns out that the obj_Test object will be redefined each time, even if the previously created thread has not yet completed.

A program with a similar implementation works correctly and no errors appear, wondering how true such an implementation is. As I thought, the name of the object of the class ThreadTest must be unique, otherwise there may be problems with redefining objects that have not yet completed their work.

  • one
    There are no names here. And there is no waiting execution. - Qwertiy
  • these are just references to an object of a class that can be referenced as many times as desired, and the thread will be created new every time, right? - Alexey
  • Yes, that's right :) - Qwertiy
  • 2
    @Alexey is true, running a little ahead - the threads themselves are GC roots, therefore, what the execution depends on will not disappear from the memory until the end of the thread. The fact that only the last object remains in the local scope is not affected by the placement of these objects in memory (in this case). Well, of course, with the proviso that a new thread is created with this object, and not .run is executed sequentially. - etki
  • one
    Please note that in your code, even though you are creating objects of the ThreadTest class (they, as I understand it, the heirs from java.lang.Thread ) are not multi-threaded. In order for the task to be executed in a separate thread, you must call the start() method. To make sure of this, make a random delay inside run() using, for example, Thread.sleep and output something to the console after the delay. - Alexandr

2 answers 2

In the specified loop, a reference is written to the reference variable obj_Test , to the object created in the heap of the class ThreadTest() . Each time the loop is iterated, the link in the obj_Test variable will be updated and refer to the new object in the heap .

This solution will not allow access, if necessary, to the objects created in the cycle ThreadTest() (except for the latter). But, on the other hand, if you do not need to access the objects created in the loop, this will save a small amount of JVM resources, since The obj_Test variable will store only one reference to the last object in the loop iteration.

    The names of the threads will be different. Will be taken from the toString created thread. Regarding the task - if the number of loop iterations should be more, then it is better to use fixed thread pool.