Java While 循环

标签 java loops if-statement while-loop irc

我在 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/

相关文章:

java - 如何从 Berkeley Aligner 读取 Alignment 类型? - java

python - 循环一列并填充函数 Pandas Dataframe Python 中的行

python - 有条件地用两个列表替换项目

groovy - Groovy:if-then语句是否具有局部作用域?

java - if 语句的低效使用 - Android

java - 在实现中使用接口(interface)类型与公共(public)接口(interface)

java - MS-Outlook PST 文件和 MS-Outlook MSG 文件之间有什么关系?

jquery - 如何仅在 jQuery 中显示 div 时运行函数?

java - 如何根据用户输入重新启动我的java程序?

c++ - 程序跳过最后一个 if 循环 c++