Java 初始化将由多个线程更新的类时出现问题

Java 初始化将由多个线程更新的类时出现问题,java,multithreading,class,Java,Multithreading,Class,嗨,我正在尝试创建一个服务器/客户端程序,该程序最多需要5个客户端,每个客户端通过多个服务器端线程输入一个字符串,这些字符串将被添加到同一个团队的团队类ie中,然后当团队已满时,客户端断开连接,服务器等待下一个团队的名称 我的问题在于创建每个线程更新到的类团队的实例。。 我不确定在哪里声明该类的实例?(它包含字符串数组[5]) 我在服务器端的类目前是“TeamServer”、“TeamServerThread”、“team”和“streamSocket” 下面是我的“TeamServerThre

嗨,我正在尝试创建一个服务器/客户端程序,该程序最多需要5个客户端,每个客户端通过多个服务器端线程输入一个字符串,这些字符串将被添加到同一个团队的团队类ie中,然后当团队已满时,客户端断开连接,服务器等待下一个团队的名称

我的问题在于创建每个线程更新到的类团队的实例。。 我不确定在哪里声明该类的实例?(它包含字符串数组[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
这是我的“团队”课程

公共类团队
{
公共最终国际团队规模=5;
公共字符串名称[]=新字符串[团队大小];
public int num_members=0;
//等待五个名字到达
//需要同步,因为它可以访问
//由多个并发线程执行
同步的空添加(字符串名称)
{
名称[num_members]=名称;
num_成员++;
if(成员数量<团队规模)
尝试
{
等待();
}
捕获(例外e){}
其他的
尝试
{
notifyAll();
}
捕获(例外e){}
}//结束添加
public int Getnum_成员()
{ 
返回num_成员;
}
}//终点队

所有类加载都是单线程的,不能使用多线程来加载/更新类。但是我想这不是你的意思

你需要一个团队,让每个插座都能看到它。你的问题是,你没有同步访问或替换团队,因此你可能会有一个竞争条件,太多的客户试图将自己添加到同一个团队中

我建议您拥有某种类型的TeamCoordinator,它被传递到每个套接字连接,这些套接字连接可以确定何时应该向团队添加客户端

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