简体   繁体   中英

How to share the same variable between class instances?

(UPDATE)So I am running a server and I want a certain number of clients to connect, so in the client class each time a client connects I increment a counter, but it does not seem to be working. I am trying to do it on the server side but its still not working

 while(true){
        try{
            Socket clientSocket = serverSocket.accept();
            MortgageRunnable m = new MortgageRunnable(clientSocket);
            System.out.println("New player has connected!");
            if(!(connectedClients == maxPlayers)){
            new Thread(m).start();
            connectedClients++;}
            else{m.displayMessage("Max players connected");}

MortgageRunnable is basically the thread so all logic is there, and this is the function displayMessage():

public void displayMessage(String message) {
    try {
        PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
        out.println(message);
}catch(IOException e){
        e.getMessage();
    }

Each time you create a new instance of Client it will re-initialize numofPlayers variable.

So, I'm going to assume you have another class which is CREATING these Client instances, let's just call that Main... I would store the counter in that 'Main' class which is spawning clients. Hopefully I understand your situation correctly.

class Main {
  public static void main(String[] args) {
    int numOfPlayers = 0;
    if (numOfPlayers < maxPlayers) {
      Client client = new Client();
      numOfPlayers++;
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM