0
嗨我想創建一個服務器/客戶端程序,最多需要5個客戶端輸入一個字符串每個通過多個服務器端線程,這些字符串將被添加到團隊類即同一個團隊,那麼當團隊已滿時,客戶端將斷開連接,服務器將等待下一個團隊的名稱。我的問題在於創建類的一個實例,每個線程更新到.. 即時通訊不知道在哪裏聲明的類的實例?(它包含一個字符串數組[5]) 我在服務器端的類當前是「TeamServer」,「TeamServerThread」,「team」,「streamSocket」啓動類將由多個線程更新的問題
下面是我的「TeamServerThread」,它接受用戶字符串並將其添加到另一個字符串中。
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
這裏是我的「團隊」類
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)
try
{
wait();
}
catch(Exception e) {}
else
try
{
notifyAll();
}
catch(Exception e){}
} // end add
public int Getnum_members()
{
return num_members;
}
} // end Team