Problems initiating class that will be updated by multiple threads
Hi i'm trying to create a sever/client program that takes up to 5 clients inputting a string each via multiple server side threads, these strings are to be added to team class ie the Same team, then when the team is full, clients disconnect and the server awaits names for the next Team.
My problem lies in creating an instance of the class Team that each thread updates to.. im not sure where to declare the instance of the class?(it contains a string array[5]) my classes on serverside are currently "TeamServer", "TeamServerThread" "team" "streamSocket"
Below is my "TeamServerThread" currently taking the user string and just adding it to another string.
import java.io.*;
class TeamServerThread implements Runnable {
static String names ="";
MyStreamSocket myDataSocket;
TeamServerThread(MyStreamSocket myDataSocket) {
this.myDataSocket = myDataSocket;
}
public void run( ) {
String newName;
try {
newName = myDataSocket.receiveMessage();
/**/ System.out.println("Name Recieved = "+newName);
updateNames(newName);
// now send the names to the requestor
// wait
myDataSocket.sendMessage(names);
myDataSocket.close();
}// end try
catch (Exception ex) {
System.out.println("Exception caught in thread: " + ex);
} // end catch
} //end run
private synchronized void updateNames (String newName) {
names +=newName + "\n";
// this.team.add(newName);
} // end updateNames
} // end Team
Here is my "Team" class
public class Team
{
public final int TEAM_SIZE = 5;
public String names[] = new String[TEAM_SIZE];
public int num_members = 0;
// waits until five names have arrived
// needs to be synchronized because it can be accessed
// by a number of concurrent threads
synchronized void add(String name)
{
names[num_members] = name;
num_members++;
if (num_members < TEAM_SIZE)
开发者_StackOverflow社区 try
{
wait();
}
catch(Exception e) {}
else
try
{
notifyAll();
}
catch(Exception e){}
} // end add
public int Getnum_members()
{
return num_members;
}
} // end Team
All class loading is single threaded and you cannot laod/update a class with multiple threads. However I assume this is not what you mean.
You need to have the Team where every socket can see it. The problem you have is that you haven't synchronized access or replacement of the Team so you could ahve a race condition where too many client try to add themselves to the same team.
I suggest you have some type of TeamCoordinator which is passed to each socket connection which can determine when Team a client should be added to.
精彩评论