具有套接字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);
}
}
}
如果我想停止运行此代码的线程,该怎么办?
在这里,它们显示了操作方法(
如何停止等待较长时间(例如,输入)的线程? ),但是我不明白它们的含义:
为了使该技术起作用,至关重要的是,任何捕获中断异常并且不准备对其进行处理的方法都必须立即重新声明该异常。我们说重新声明而不是重新抛出,因为并非总是可能重新抛出异常。如果未声明捕获InterruptedException的方法引发此(检查的)异常,则它应使用以下提示“重新中断自身”:Thread.currentThread()。interrupt();
谁能给我一些提示吗?一些代码示例将不胜感激。
问题答案:
彼得·劳瑞(Peter Lawrey)描述并在此看到的解决方案是关闭插座。
使用nio,您还可以使用可中断的SocketChannel并允许应用Java的标准中断模型。
调用Thread对象的interrupt方法会引发InterruptedException,该异常甚至会停止您的阻塞IO操作。