2012-09-07 31 views
4

在我的服务器应用程序的某个时候,我想停止一些正在执行I/O阻塞操作的线程。带插座I/O阻塞操作的中断/停止线程

例如,其中一人有以下run()方法:

public void run() { 
    System.out.println("GWsocket thread running"); 

    int len; 
    byte [] buffer = new byte[1500]; 
    try { 
     this.in = new DataInputStream(this.socket.getInputStream()); 
     this.out = new DataOutputStream(this.socket.getOutputStream()); 
     running = true; 

     while (running){ 
      len = in.read (buffer); 
      if (len < 0) 
       running = false; 
      else 
       parsepacket (buffer, len); 
     } 

    }catch (IOException ex) { 
     System.out.println("GWsocket catch IOException: "+ex); 
    }finally{ 
     try { 
      System.out.println("Closing GWsocket"); 
      fireSocketClosure(); 
      in.close(); 
      out.close(); 
      socket.close(); 
     }catch (IOException ex) { 
      System.out.println("GWsocket finally IOException: "+ex); 
     } 
    } 
} 

如果我想停止运行此代码线程,我应该怎么办?

Here他们如何做,但我不明白他们的意思与(如何停止等待很长时间(例如,用于输入一个线程)):

为了使这种技术起作用,任何能够捕获中断异常并且不准备立即处理它的方法 重申异常是至关重要的。我们说reasserts而不是rethrows, ,因为它不总是可能重新抛出异常。如果 方法捕获InterruptedException的没有声明抛出 这个(选中)异常,那么就应该“reinterrupt本身”与 以下咒语:Thread.currentThread()中断()。

谁能给我一些提示?一些代码示例将非常感谢。

回答

6

您可以添加一个方法类似

public void close() throws IOException { 
    this.socket.close(); 
} 

任何阻塞的IO操作将引发SocketException。

你可能想设置一个标志,像closed,你可以检查是否抛出的异常是可以预料的或没有。

BTW:你不能肯定,你会得到一个读离散包。阅读所需内容并使用BufferedInputStream来提高效率要好得多。如果您不需要分析内容从套接字复制到文件。

例如你的读取只能得到一个字节,或者得到一个数据包的结束和另一个数据的开始。

+0

嗨,谢谢你的回答。有时'len = in.read(buffer);'给了我一个IOException ...可能是因为我使用'DataInputStream'而不是'BufferedInputStream'? – amp

+0

您将哪个流包裹起来没有任何区别。 –