-2

The program I am creating requires an array of thread objects. More specifically I have a class which extends Thread. I am doing this so that each new object created runs on its own thread. If I want to kill the thread and remove it from the array element, so that I can create a new Thread object in that space, how do I do this? This is my thought.

I understand that removing reference to the thread will not actually stop the thread. To do this I would first need to interrupt the thread. To remove the thread object from the array, can I simply make it null? I.e.:

array[i].interrupt();    
array[i] = null;

And then I would be able to create a new thread in that space?

array[i] = new Thread();

Assume that the run method of the Thread objects handles interruptions properly etc.

Simas
  • 11

1 Answers1

0

To remove the thread object from the array, can I simply make it null

Yes. This should make the reference held at index position i to point to null. However, if you are setting the element at index position i to null and then immediately saying array[i] = new Thread();, you can skip the step where you set it to null and only use array[i] = new Thread(); instead.

Also note that just adding the element to the array won't start the newly inserted Thread. You would still need to call array[i].start() after inserting the new Thread in the array to start the new Thread.

That said, extending from Thread makes sense only if you plan to override some of the functionalities from the Thread class. (I personally don't see any valid use case for this). You should instead implement Runnable and pass it to the Thread constructor.

Chetan Kinger
  • 15,069
  • 6
  • 45
  • 82