使线程中断的正确方法是在线程类里设置一个标志,通过改变这个标志来使线程退出,强行中断线程可能会带来意想不到的结果,如下所示: public void run() { while (true) { // do something .... if (finished) // finished is a boolean variable break; } }
大致代码如下 public class InfoRece extends Thread { boolean shouldBeKilled; Socket socket; /* ...... */ public void run() { try { inn = socket.getInputStream(); out = socket.getOutputStream(); } catch(Exception ex) { System.err.println("InfoRece1:"+ex); } try { while(true) { String info = readInfo(inn); /* ... */ } } catch(Exception ex) { shouldBeKill = true; System.err.println("infoRece2 :"+ex); break; }
try { socket.close(); } catch(Exception e) { } }
public String readInfo(InputStream in) throws Exception { int len = 0; byte[] b = new byte[1024]; String str = null; try { while((len = in.read(b,0,b.length)) != -1) { /* ... */ return str; } } catch(Exception ex) { System.err.println(ex); return str; } }
}
然后我在另外一个线程将该线程 t.interrupt() ; t = null;在String info = readInfo(inn); 输出info, 该线程仍然能输出信息。也无法捕获任何异常
public void run() {
while (true) {
// do something
.... if (finished) // finished is a boolean variable
break;
}
}
public class InfoRece extends Thread
{
boolean shouldBeKilled;
Socket socket;
/*
......
*/ public void run()
{
try
{
inn = socket.getInputStream();
out = socket.getOutputStream();
}
catch(Exception ex)
{
System.err.println("InfoRece1:"+ex);
}
try
{
while(true)
{
String info = readInfo(inn);
/*
...
*/
}
}
catch(Exception ex)
{
shouldBeKill = true;
System.err.println("infoRece2 :"+ex);
break;
}
try
{
socket.close();
}
catch(Exception e)
{ }
}
public String readInfo(InputStream in) throws Exception
{
int len = 0;
byte[] b = new byte[1024];
String str = null;
try
{
while((len = in.read(b,0,b.length)) != -1)
{
/*
...
*/
return str;
}
}
catch(Exception ex)
{
System.err.println(ex);
return str;
} }
}
t.interrupt() ;
t = null;在String info = readInfo(inn);
输出info,
该线程仍然能输出信息。也无法捕获任何异常
但是你没用它监测线程呀???
其实用interrupt(),再检测interrupted()就可以了
t为InfoRece的一个线程
t.interrupt() ;
t = null;
if(shouldBeKill)break;
在
monitor守护线程里将
t.shouldBeKill = true;
t.interrupt() ;
t = null;
这样可以在该socket执行完readinfo()后break,终止线程
主要的问题是len = in.read(b,0,b.length)) != -1是阻塞的,
在一个client 连接上server建立socket,但是不发出数据的话,线程会一直阻塞在len = in.read(b,0,b.length)) != -1这里,无法中断他,
好办,在你的线程t.start()之后紧接着调用
try{t.join(timeout);}
catch(InterruptedException e){}
其中timeout是连接超时,单位毫秒,就行了不过,你的程序,我看起来总觉得结构有点别扭,看看Core Java chapter3,
可能对你有很大的帮助,尤其是你的程序的结构