It is possible to add elements to arraylist while other thread, reading the arraylist in same time, get notified about this changes?
For example i have an arraylist in main thread. There is 4 elements:
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
Meantime, other thread add elements in same list:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 5; i < 10; i++) {
list.add(i);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
thread.start();
Now i start reading them like:
for (int i : list) {
System.out.println(i);
Thread.sleep(2000);
}
I want to read all elements from 1 to 9, but this is not work. How i can pull off this? Maybe i should put synchronized block in this code, but where should i?