当前位置: 技术问答>java相关
求教:这个线程为什么停不下来?
来源: 互联网 发布时间:2015-06-20
本文导语: 在主程序中调用另一个类(是Thread的子类)的run()方法,当主程序结束时,线程并不结束,直至出现 java.io.InterruptedIOException: Read timed out异常。为什么? 分一定会送,谢谢!! 附被调用类的代码: class HandleServ...
在主程序中调用另一个类(是Thread的子类)的run()方法,当主程序结束时,线程并不结束,直至出现 java.io.InterruptedIOException: Read timed out异常。为什么?
分一定会送,谢谢!!
附被调用类的代码:
class HandleServerInput extends Thread{
private Socket incom;
public HandleServerInput(Socket x){
incom=x;
}
public void run(){
try{
BufferedReader serverin = new BufferedReader(new
InputStreamReader(incom.getInputStream()));
while (true){
String str2=serverin.readLine();
System.out.println(str2);
}
}
catch(Exception e){
System.out.println("The runner is wrong with "+e); }
}
}
分一定会送,谢谢!!
附被调用类的代码:
class HandleServerInput extends Thread{
private Socket incom;
public HandleServerInput(Socket x){
incom=x;
}
public void run(){
try{
BufferedReader serverin = new BufferedReader(new
InputStreamReader(incom.getInputStream()));
while (true){
String str2=serverin.readLine();
System.out.println(str2);
}
}
catch(Exception e){
System.out.println("The runner is wrong with "+e); }
}
}
|
一个很简单的方法,就是把你要调用的线程设置成Daemon线程(精灵线程)它不依赖于其他线程,如果主线程结束,那么它会自己结束,不用你写代码让它结束,一般它用来维护其他线程的,但自己不用其他线程来维护。
只要在你调run方法前setDaemon(true)就可以了,你试一试。
只要在你调run方法前setDaemon(true)就可以了,你试一试。
|
while (true)
{
String str2=serverin.readLine();
System.out.println(str2);
}
改为:
while (true)
{
String str2=serverin.readLine();
System.out.println(str2);
if(str2.equalsIgnoreCase("end"))
break;
}
{
String str2=serverin.readLine();
System.out.println(str2);
}
改为:
while (true)
{
String str2=serverin.readLine();
System.out.println(str2);
if(str2.equalsIgnoreCase("end"))
break;
}
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。