整数不会增加?

时间:2010-09-28 17:08:40

标签: java multithreading networking integer

好的,所以我正在进行客户端/服务器测试,我将Integer playerID传递给一个线程,它将int值赋给一个简单的Player对象,而不是将playerID增加1。

 public static void main(String[] args) throws IOException {

        Vector<Player> player = new Vector<Player>();

        SlickServer ss = new SlickServer();
        ss.setVisible(true);

        ServerSocket serverSocket = new ServerSocket(4444);
        boolean listening = true;

        Integer playerID = new Integer(0);

        while(listening){
            ss.textArea.append("Waiting to connect with player: " + playerID.intValue()  + "\n");
            new ClientThread(serverSocket.accept(), player, playerID, ss.textArea).start();
            ss.textArea.append("Waiting to connect with player: " + playerID.intValue() + "\n");
        }

        serverSocket.close();
        System.exit(0);
    }

以及它在线程中增加它的位置:

public ClientThread(Socket acceptedSocket, Vector<Player> players, Integer playerID, JTextArea textArea){
        super("ClientThread");
        this.acceptedSocket = acceptedSocket;
        this.players = players;
        players.add(new Player(50,50, playerID.intValue()));

        if(players != null)
            System.out.println("Not Null: " + players.size());

        boolean b = false;
        for(int i = 0; i < players.size(); i++){
            if(!b){
                if(players.get(i).id == playerID){
                    me = players.get(i);
                    b = true;
                }
            }
        }

        playerID = new Integer(playerID.intValue() + 1);
        this.textArea = textArea;
    }

4 个答案:

答案 0 :(得分:7)

new Integer正在客户端线程方法中创建一个全新的Integer实例,调用者无法使用该实例。

但是,您需要考虑主线程和客户端线程之间的同步。对于非平凡对象使用synchronized语句或对整数使用java.util.concurrent.atomic.AtomicInteger类可以实现这一点,如下所示:

AtomicInteger playerID = new AtomicInteger(0);
while (listening) {
  ss.textArea.append("Waiting to connect with player: " + playerID.get()  + "\n");
  new ClientThread(serverSocket.accept(), player, playerID, ss.textArea).start();
  ss.textArea.append("Waiting to connect with player: " + playerID.get() + "\n");
}

class ClientThread {
  public ClientThread(Socket acceptedSocket, Vector<Player> players, AtomicInteger playerID, JTextArea textArea) {
    // etc.
    playerID.incrementAndGet();
    // etc.
  }
}

您需要考虑如何在并发执行的线程之间共享数据。这也适用于Vector<Player>JTextArea参数。您应该根据需要使用players语句包含对textAreasynchronize对象的访问。

答案 1 :(得分:2)

创建main后,在ClientThread中增加玩家ID。

客户端线程不应负责增加玩家ID。这是main的责任,{{1}}是创建客户端线程并为其提供ID的人。

答案 2 :(得分:0)

如果需要,请尝试使用IntHolder

答案 3 :(得分:0)

如果要在方法中操作整数,则需要将其封装在对象中。

阅读本文以便更好地理解 http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html