Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is Thread detecting two objects even though one was created?

public class ThreadExample {

    public static ArrayList<ThreadExample> instances = new ArrayList<ThreadExample>();

    public ThreadExample() {
        instances.add(this);
    }

    public static void main(String[] args) {
        ThreadRead threadRead = new ThreadRead();
        ThreadCreate threadCreate = new ThreadCreate();
        threadCreate.start();
        threadRead.start();

    }

}

class ThreadRead extends Thread {
    public void run() {
        System.out.println(ThreadExample.instances.size());
    }
}

class ThreadCreate extends Thread {
    public void run() {
        ThreadExample.instances.add(new ThreadExample());
    }
}

The output of the code is "2"

The output I expected from the code was 1 or 0. Because if ThreadCreate reads ThreadRead at the same time while creating an object, I could expect "0" to come up because it will read before the construction of the object is completed. Or everything would go well and I would get the result "1". What is going on here that I don’t know?

Thanks.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Because you added twice.
You add a object.

ThreadExample.instances.add(new ThreadExample());

And you add again

instances.add(this);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading