Jim
Jim

Reputation: 4415

Why there are two running threads instead of one?

So in the following:

public class JavaClass {
    public static void main(String[] args) {
        JavaClass clazz = new JavaClass();
        clazz.startCustomThread();

        clazz = new JavaClass();
        clazz.startCustomThread();
    }

    public void startCustomThread() {
        new MyThread().startThread();
    }

    private static class MyThread {
        public void startThread() {
            new Thread(() -> {
                System.out.println("In thread " + Thread.currentThread().getName());
                while (true) {
                    try {
                        Thread.sleep(1000 * 5);
                        System.out.println("Woke up " + Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }).start();
        }
    }
}

The output is:

In thread Thread-1
In thread Thread-0
Woke up Thread-0
Woke up Thread-1
....  

Since the clazz should be GC'd after the second instance and the first thread started in local scope of the first call to startCustomThread()
my question is why doesn't the first thread get terminated?

Upvotes: 1

Views: 92

Answers (3)

star67
star67

Reputation: 1832

The line clazz = new JavaClass(); is just assigning new object to your local reference and doesn't destruct previously created object this reference was referred to. This line doesn't guarantee the object is garbage collected.

Also object's garbage collection is not necessarily related to thread's lifecycle - your thread can be interrupted or finish its execution but object still may exist in the heap and being waited for GC.

Upvotes: 1

cameron1024
cameron1024

Reputation: 10186

If you are asking specifically about why the JavaClass objcet is not GC'ed. it probably is (depending on VM parameters).

If you are asking why the thread spawned by that object continues to run, it is because it creates a new Thread and runs it. This will only finish when either the run() method finished normally, or System.exit() is called.

Upvotes: 2

Michał Krzywański
Michał Krzywański

Reputation: 16910

You invoked startCustomThread method twice so you have started 2 Threads.

From Thread docs :

The Java Virtual Machine continues to execute threads until either of the following occurs:

  1. The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
  2. All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.

No of those options applies to your case so the thread is still alive. This has nothing to do with garbage collection.

Upvotes: 2

Related Questions