简体   繁体   English

如何在类实例之间共享相同的变量?

[英]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(): MortgageRunnable 基本上是线程,所以所有逻辑都在那里,这是函数 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.每次创建 Client 的新实例时,它都会重新初始化 numofPlayers 变量。

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.因此,我将假设您有另一个类正在创建这些客户端实例,让我们将其称为 Main...我会将计数器存储在生成客户端的“Main”类中。 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++;
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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