This is my first time using the synchronized
keyword, so I am still unsure of how it exactly works. I have a list that I want to be accessed by multiple threads so I do this:
players = Collections.synchronizedList(new ArrayList<Player>(maxPlayers));
Now, I want to make sure that I am not calling players.add()
at the same time as players.get()
, so I think i should use synchronized statements (methods A and B could be called at the same time):
public void A() {
synchronized(players) {
players.add(new Player());
}
}
public void B(String msg) {
synchronized(players) {
for(int i = 0;i<players.size();i++) {
players.get(i).out.println(msg);
}
}
}
Is this the correct procedure? If not, what should I do instead?