-2

If I have a Thread running in a class called Menu, what happens to the thread if I were to reinitialize Menu?

public class Menu {
    private Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            while(!thread.isInterrupted()){
                // Thread code
            }   
        }
    });

    public Menu() {
        thread.start();
    }

    public static void main(String[] args) {
        Menu menu = new Menu(); //Original
        menu = new Menu(); // New
    }

}

Does the thread in the original initialization continue running along with the new one or does it stop?

*Edited in attempt to make it clearer although I got my answer.

Crimson Bloom
  • 287
  • 2
  • 13

2 Answers2

2

If the Menu is not launching new threads, then there is nothing to talk of about. But, if the Menu does things in threads (something like):

void doStuff() {
    new Thread(()->{
    //do work here
    }).start();
}

or may be in the constructor (Don't do this - causes reference escape causes thread unsafe operations) itself:

Menu() {
  //create a thread here
}

the reference to this object is still in use by the newly spawned thread, even if you change the reference where you created a new instance:

public static void main(String[] args) {
    Menu menu = new Menu();//initialize --> spawned a new thread here
    menu.doStuff();  // --> or here depending on where you did it
    int x = menu.getNumbers;
    menu = new Menu(); //reinitialize
}

Reinitialising the variable menu will not kill the thread. The thread will run to its completion.

Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
  • 1
    As a general rule, btw, you shouldn't be starting new threads from a constructor if those threads will ever reference the object being constructed. That's not thread safe. In other words, in the example here, if the newly started thread accessed any instance methods on Menu, it's probably unsafe. – yshavit Dec 25 '16 at 06:23
  • @yshavit That's correct. That causes reference escape. – Gurwinder Singh Dec 25 '16 at 06:24
-1

As explained in this link Java Thread Garbage collected or not

As long as a thread is live, meaning that it is still running code then the thread will continue to run even though though a reference to that thread object is lost. This is due to the nature of the garbage collector, that it will not destroy a live thread (Think why the main thread never gets destroyed even though there is no reference).

This is why even if you lose a reference to an object that has a thread in it, like the object Menu in your case, the thread will still run until it finishes.

Community
  • 1
  • 1
SteelToe
  • 2,477
  • 1
  • 17
  • 28