简体   繁体   English

实例的Java静态变量是否在另一个实例中被覆盖?

[英]Java Static Variable of instance overwritten in another instance ?

Im suffering from more complex problem. 我患有更复杂的问题。 I 've got server program, when server accepts connection it creates new socket and communicate throught it in new thread. 我有服务器程序,当服务器接受连接时,它将创建新的套接字并在新线程中进行通信。 This new thread creates an instance of class 'Protocol' and class protocol contains static variable. 这个新线程创建了一个类'Protocol'的实例,并且类协议包含静态变量。

static Player player; 

This class contains method where in which this player variable is initialized. 此类包含其中初始化播放器变量的方法。 There is the code sample 有代码示例

synchronized(pMap){
    if (pMap==null || pMap.PlayerNumber>3)
        return false;
    player = pMap.createPlayer(Thread.currentThread().getId());
}

When first player joins everything works fine, but when the 2nd player joins server, calls this method within his thread (2nd thread) and creates new protocol instance, variable Player in 1st thread cointains new instance of player(instance created in 2nd thread) instead of instance created when there was no second thread. 当第一个玩家加入时一切正常,但是当第二个玩家加入服务器时,在其线程(第二个线程)中调用此方法并创建新的协议实例,第一个线程中的变量Player会包含玩家的新实例(在第二个线程中创建的实例)没有第二个线程时创建的实例的实例。

Long story short, all new threads always have same Player instance, even that in every thread there is always created new instance of Player. 简而言之,所有新线程始终具有相同的Player实例,即使在每个线程中始终都创建了Player的新实例。 Im new to OOP, maybe im not understand correctly the meaning of 'static'. 我是OOP的新手,也许我无法正确理解“静态”的含义。 I would be glad if someone could explain this :-) . 如果有人可以解释一下,我会很高兴的:-)。

static means "shared among all instances". static表示“在所有实例之间共享”。 It appears that your code has some logic that prevents creation of more than three players at the same time. 您的代码似乎具有某种逻辑,可以防止同时创建三个以上的播放器。 In this case, it is incorrect to assign players to a shared static variable. 在这种情况下,将玩家分配给共享的static变量是不正确的。

You should make Player non-static in your class, or at the very least use a thread-local storage for it . 您应该在类中将Player非静态,或者至少使用它在线程本地存储 Otherwise, all instances of your Protocol are going to share the same player, regardless of the thread on which they run. 否则, Protocol所有实例都将共享同一播放器,而不管它们运行在哪个线程上。

static variable is not an instance variable, its the same one for every instance. 静态变量不是实例变量,每个实例都相同。 its a class variable so if some instance touch it, it will change for all. 它是一个类变量,因此如果某个实例触摸到它,则所有变量都会改变。 you can read more about static variables here 您可以在此处阅读有关静态变量的更多信息

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

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