我目前正在为多人游戏编写服务器。服务器的主要类如下:
public final Logger logger = LogManager.getLogger(Turtle.class.getName());
public boolean isStopped = true;
public static Turtle serverInstance;
public NetworkHandler networkHandler;
protected InetAddress ip;
protected int port;
public Turtle(InetAddress ip, int port){
this.ip = ip;
this.port = port;
}
public static void main(String[] args){
serverInstance = new Thread(new Turtle(NetworkHandler.getipByName("0.0.0.0"), 19132));
serverInstance.start();
}
public void run() {
logger.info("Starting Turtle...");
isStopped = false;
logger.info("Initializing Networking.");
networkHandler = new NetworkHandler(ip, port);
networkHandler.start();
logger.info("Done!");
}
public NetworkHandler getNetworkHandler(){
return networkHandler;
}
public static Thread getServer(){
return serverInstance;
}
public static String getMOTD(){
return "MCCPP;MINECON;[0/20] Turtle Test Server";
}
public Logger getLogger(){
return logger;
}
public void stop(){
logger.info("Turtle is stopping.");
networkHandler.stahp();
System.exit(0);
}
这个类本身就是一个Runnable。如您所见,我尝试通过将静态serverInstance设置为线程中服务器的实例来启动服务器,然后通过调用start方法。但是,这不起作用,因为serverInstance需要Turtle对象(此类的名称)。我无法将其更改为Thread,因为程序的其他部分需要通过此实例使用Turtle中的方法,并且将serverInstance更改为Thread不会让我访问该类的任何方法。
所以,问题是,如何将serverInstance设置为此线程,并保留对serverInstance中所有Turtle方法的访问权限?
很抱歉,如果这有点令人困惑。我的脑子里也有点混乱,我可能遇到了一些麻烦。
答案 0 :(得分:0)
这有效吗?:
public static Turtle globalTurtle;
public static Thread serverInstance;
public static void main(String[] args){
globalTurtle = new Turtle(NetworkHandler.getipByName("0.0.0.0"), 19132);
serverInstance = new Thread(globalTurtle);
serverInstance.start();
}
(还有所有其他线......)