Question

What will happen if I assign a new thread object to a thread variable and run it while the thread object that was bound to the variable before is still running? Will it be garbage collected and destroyed? Or will they run in parallel?

Something like this:

class ThreadExample implements Runnable {
    public void run() {
        // Something that runs for a long time
    }
}

public class ThreadExampleMain {
    public static void main(String[] args) {
        // Client Code
        ThreadExample e = new ThreadExample();
        Thread t = new Thread(e);
        t.start();

        e = new ThreadExample();
        t = new Thread(e);
        t.start();
    }
}

Will this start two threads running parallelly or will the first thread stop and be garbage collected?

Was it helpful?

Solution

If you a talking about Java then answer is: they will run in parallel. Garbage collection has nothing to do with the thread management.

You can see it with this sample code:

public class LostThread {
    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            final int value = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (true) {
                        try {
                            System.out.println(value);
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        }
    }
}

Main finishes after ten threads are created, but they are still running.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top