I have written the below program that would create three threads and start them. The task for each thread is to iterate a list of strings. This list is a synchronizedList. When I run the program, I still see the thread output not synchronized. i.e., Before the first thread iterates through everything in the list, the second one interrupts and third one and so forth
import java.util.*;
public class Program implements Runnable{
List<String> stars = Collections.synchronizedList(new ArrayList<String>());
public static void main(String[] ars){
System.out.println(Thread.currentThread().getName());
Program p = new Program();
p.init();
}
public void init(){
stars.add("Tom Hanks");
stars.add("Bruce Lee");
stars.add("Matthew");
stars.add("fasbender");
stars.add("pitt");
Thread one = new Thread(this);
one.setName("First");
Thread two = new Thread(this);
two.setName("Two");
Thread three = new Thread(this);
three.setName("Three");
one.start();
two.start();
three.start();
}
public void run(){
for(int i=0;i<stars.size();i++){
System.out.println(stars.get(i)+" "+Thread.currentThread().getName());
}
}
}
I was expecting the output as: main Tom Hanks First Bruce Lee First Matthew First fasbender First pitt First Tom Hanks Second Bruce Lee Second Matthew Second fasbender Second pitt Second Tom Hanks Third Bruce Lee Third Matthew Third fasbender Third pitt Third
But when i run the program, the actual output is like:
main
Tom Hanks First
Bruce Lee First
Matthew First
fasbender First
pitt First
Tom Hanks Three
Tom Hanks Two
Bruce Lee Three
Bruce Lee Two
Matthew Three
Matthew Two
fasbender Three
fasbender Two
pitt Three
pitt Two