2011-04-04 26 views
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 

回答

0

所有的类加载是单线程的,你不能LAOD /更新多个线程的类。不过,我认为这不是你的意思。

您需要让每个套接字都可以看到的团队。你的问题是你没有同步访问或更换团队,所以你可能会遇到太多客户试图将自己添加到同一个团队的竞争条件。

我建议你有一些类型的TeamCoordinator传递给每个套接字连接,它可以确定何时应该添加一个客户端。