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.
>Solution :
Because you added twice.
You add a object.
ThreadExample.instances.add(new ThreadExample());
And you add again
instances.add(this);