我在 while 循环方面遇到了一些问题。这个 while 循环在线程中运行,并且是线程的“主循环”,如果它循环的 if 语句之一为 false,我会遇到问题,它不会继续。该线程处理发送和接收 IRC 命令/消息以在 Minecraft 客户端中使用。
目前的代码如下:
do {
System.out.println("IRC Thread Looped!");
if(tosend != "") {
writer.write("PRIVMSG " + channel + " :"+tosend+"\r\n");
System.out.println(tosend);
mc.thePlayer.addChatMessage("\247f[\247bIRC\247f] \2477"+nick+": \247f"+tosend);
tosend = "";
writer.flush();
}
if((line = reader.readLine()) != null) {
if(line.startsWith("PING ")) {
writer.write("PONG " + line.substring(5) + "\r\n");
writer.flush( );
}
else {
// we need to pretty this ugly sh*t up!
try {
String parsedline;
String args[] = line.split("!");
String args2[] = args[1].split(":");
args[0] = args[0].substring(1, args[0].length());
parsedline = "\2477"+ args[0] +": \247f"+ args2[1];
mc.thePlayer.addChatMessage("\247f[\247bIRC\247f] "+parsedline);
}
catch(Exception e) {
mc.thePlayer.addChatMessage("\247f[\247bIRC\247f]\247f "+line);
continue;
}
}
}
try {
Thread.sleep(90L);}catch(Exception e) { };
}
} while(true);
最佳答案
请注意,java 线程喜欢吃掉 run() 方法抛出的异常。
由于您的 IO 诸如 if((line = reader.readLine()) != null){
不在 try/catch 中,因此您可能会抛出异常并退出。
我喜欢对线程做的事情是将主线程代码放在 runImpl()
中,并使 run()
看起来像这样。
public void run()
{
try
{
runImpl();
}
catch( Throwable t )
{
// log the throwable
}
}
那么至少你可以发现你的线程抛出了一些意想不到的东西。
关于Java While 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6991208/