Synchronizing lst on your code does not stop you add or delete the element in the list in order,
because both the operations (add and delete method are not atomic in your case.)
Think like this
Lets say there are two thread A and B.
Thread A tries to add the element to List in your case it will add Ram first then it releases the lock when the method completes and go to next line in the run method try to call the add method again ...during which time thread B can get the lock lst object and never give a chance to thread A and add all the elements to the lst and when thread B calls display method it will also display the Ram added by Thread A so in this case Ram will be displayed twice.
This kind of situation can happen in your program between each thread.
So in order to avoid this problem all the operation on the lst should be atomic.
This could work
inside run metod
now this will work the way we want as both the add and delete operation are atomic.
hope this helps you.
SCJP 6,SCWCD 5,SCBCD 5
Failure is not an option.
Joined: Mar 26, 2009
thanks Siva for the nice explanation.
subject: synchronizing on public member of type ArrayList<String>