Okay, so I have a client/server test going on, and I am passing the Integer playerID to a thread where it gives the int value to a simple Player object, than increments playerID by 1.
public static void main(String[] args) throws IOException {
Vector<Player> player = new Vector<Player>();
SlickServer ss = new SlickServer();
ss.setVisible(true);
ServerSocket serverSocket = new ServerSocket(4444);
boolean listening = true;
Integer playerID = new Integer(0);
while(listening){
ss.textArea.append("Waiting to connect with player: " + playerID.intValue() + "\n");
new ClientThread(serverSocket.accept(), player, playerID, ss.textArea).start();
ss.textArea.append("Waiting to connect with player: " + playerID.intValue() + "\n");
}
serverSocket.close();
System.exit(0);
}
and here’s where it increments it in the thread:
public ClientThread(Socket acceptedSocket, Vector<Player> players, Integer playerID, JTextArea textArea){
super("ClientThread");
this.acceptedSocket = acceptedSocket;
this.players = players;
players.add(new Player(50,50, playerID.intValue()));
if(players != null)
System.out.println("Not Null: " + players.size());
boolean b = false;
for(int i = 0; i < players.size(); i++){
if(!b){
if(players.get(i).id == playerID){
me = players.get(i);
b = true;
}
}
}
playerID = new Integer(playerID.intValue() + 1);
this.textArea = textArea;
}
new Integeris creating a brand-newIntegerinstance inside the client thread method which is not available to the caller.However, you need to consider synchronization between the main and client thread. This can be achieved using
synchronizedstatements for nontrivial objects or classes such asjava.util.concurrent.atomic.AtomicIntegerfor integers as follows:You need to think about how to share data between concurrently executing threads. This applies also to the
Vector<Player>andJTextAreaarguments. You should wrap accesses to theplayersandtextAreaobjects usingsynchronizestatements as appropriate.