setSoTimeout
public void setSoTimeout(int timeout)
                  throws SocketException
Enable/disable SO_TIMEOUT with the specified timeout, in milliseconds. With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.io.InterruptedIOException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.

解决方案 »

  1.   

    就socket连接来说,Socket和ServerSocket都有setSoTimeout方法,可以设超时。
      

  2.   

    我明白了一点。我还想问一下,java怎么做一定时器?假如用定时器的方式来实现上述的超时问题,有什么不妥吗?
      

  3.   

    可以用定时器来实现,这样CPU多了层开消。如果想在超时后进行相应处理,你可以捕捉超时异常来实现。
      

  4.   

    我明白。但我还想问一下,用java怎么来做一定时器?
      

  5.   

    关于TimerTask,能更具体一点吗?我是JAVA的初学者,有劳兄弟!