3

如果需要的时间超过 2 秒,是否有一种简单的方法可以跳过 java 中的 readLine() 方法?

这是我提出这个问题的背景:

public void run()
{
    boolean looping = true;
    while(looping) {
        for(int x = 0; x<clientList.size(); x++) {
            try {
                Comm s = clientList.get(x);
                String str = s.recieve();
                // code that does something based on the string in the line above
            }
            // other stuff like catch methods
        }
    }
}

Comm是我写的一个类,receive方法,里面包含一个叫“in”的BufferedReader,是这样的:

public String recieve()
{
    try { if(active) return in.readLine(); }
    catch(Exception e) { System.out.println("Comm Error 2: "+e); }
    return "";
}

我注意到程序停止并等待输入流在继续之前有要读取的内容。这很糟糕,因为我需要程序继续循环(当它循环时,它会转到所有其他客户端并要求输入)。如果没有什么可读的,有没有办法跳过 readLine() 过程?

我也很确定我没有很好地解释这一点,所以如果我感到困惑,请向我提问。

4

1 回答 1

4

单独的超时不是一个好主意。每个客户端使用一个线程(或使用异步 I/O,但除非您正在构建一些高性能应用程序,否则这会不必要地复杂)。

至于超时本身,必须在封装好的流上完成。例如,请参阅如何根据 Java 中的 URLConnection 对 BufferedReader 设置超时?

于 2010-05-18T22:43:56.847 回答