【发布时间】:2012-09-01 03:54:28
【问题描述】:
在我的服务器应用程序的某个时刻,我想停止一些正在执行 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 他们展示了如何做(如何停止等待长时间(例如,输入)的线程?),但我不明白它们的含义:
要使这项技术发挥作用,任何能够捕捉到的方法都至关重要 中断异常,不准备立即处理 重申例外。我们说重新断言而不是重新抛出, 因为并不总是可以重新抛出异常。如果 捕获 InterruptedException 的方法未声明为抛出 这个(检查的)异常,那么它应该“重新中断自己” 以下咒语:Thread.currentThread().interrupt();
谁能给我一些提示?一些代码示例将不胜感激。
【问题讨论】:
标签: java multithreading sockets