I'm having a bit of difficulty understanding how to synchronize ArrayList's between threads in java. Currently my code looks like:
Public class Runner {
public static void main(String argv[]) {
Connect f = new Connect(irc.freenode.net, 6667);
Thread ft = new Thread(f);
ft.start();
Connect q = new Connect(irc.quakenet.org, 6667);
Thread qt = new Thread(q);
qt.start();
MessageParser mp = new MessageParser(f);
MessageParser mp = new MessageParser(q);
f.addMessage("Hello!");
q.addMessage("World!");
}
}
public class Connect {
public List<String> l = new ArrayList<String>();
public static void addMessage(String str) {
l.add(str);
}
}
The example is just to show what I'm doing, it isn't meant to make sense heh. Anyway I wanted to see if it was possible to have my ArrayList 'l' synched up between both threads. So that running f.addMessage("Hello!"); and q.addMessage("World!");, both messages will be readable by either class. I know I could just easily make a seperate class that handles the ArrayList and pass it to both Connect classes but I wanted to see if there was an alternate way. I know about using a synchronizedList but I'm not very sure how that works and if it is applicable to my situation.
Thanks.