I have two classes
classA {
private ArrayList<String> list = new ArrayList();
void addString(String s){
list.add(s);
}
void start(){
new ClassB(list).start();
}
}
classB extends Thread{
ArrayList<String> s;
public ClassB(ArrayList<String> s) { this.s = s; }
void run(){
for (String s1 : s){
// print s1
}
}
}
Now when I write code as
ClassA A = new ClassA();
A.addString("1");
A.addString("2");
A.addString("3");
A.start();
I want run() in classB to print all elements in list. i.e (1, 2, 3) in this case.
Is this always default or do we need to do apply multi threading concepts to make it happen?
What if list is non-volatile? Can new thread see all the elements (1,2,3)
What if I add another element after A.start() (say A.addString("4") ), then what should I do to make new thread print all 4 elements?
ConcurrentModificationException. You have to use a synchronized version of your list. Even if you fix that your thread B might or might not output the value from your collection. You have to add some logic to let the thread know it has to wait for new elements and then print them once they added.