In my Android app, I have a class that extends Thread that runs when there’s an established internet connection (3G/WIFI).
When the app is loaded, if an internet connection is established, I instantiate the class like this:
MyThread thread = new MyThread(); // (it calls its own start() method)
In the thread, if the connection is lost, I want to destroy the Thread. I was told not to run finalize(), how would I destroy it so that thread == null is true?
Edit: The reason I was asking was, later on, I would like to restart the thread in case connectivity returned, and a check to see if (thread == null) would have been easy. I could just use a flag to indicate the thread needs to be restarted or check to see if it was interrupted. Thanks for the helpful comments so far.
Generally, you don’t subclass
Thread. You create aRunnable, and pass it into aThreadobject, or better yet, anExecutorService.But you don’t have to worry about cleaning up after the thread is done, it will be handled automatically by the garbage collector. If you want your own local reference to be null, just null it out yourself, or better yet, don’t hang on to it.