【发布时间】:2012-03-13 19:34:05
【问题描述】:
我试图关闭作为多线程服务器一部分的当前线程。 线程已准备好打开客户端可以访问的套接字。
一切正常,除非下面的代码包含在 while() 循环中。
new ServerThread(serversocket.accept(), this.Rstr, bag.numberofDatatoAcquire).start();
这是服务器的代码:
public void run() {
System.out.println("This has been called ");
try{
System.out.println("This has been tried");
serversocket = new ServerSocket(this.iPort);
Thread thisThread = Thread.currentThread();
while(!thisThread.isInterrupted()){
new ServerThread(serversocket.accept(), this.Rstr, bag.numberofDatatoAcquire).start();
//sending socket accessed, where it will store the data and how much it will collect it.
System.out.println("This has been running");
Thread.sleep(10);
}
}catch(InterruptedException e){
//why bother? it is an usual happening...lol
}catch(IOException ioe)
{
System.err.println("Can't open the socket on port");
}
finally{
System.out.println("Thread is dead and ready for change");
}
}
这是 GUI 事件的一部分:没有“新的 ServerThread...”代码也能正常工作。
private OverWatch EW = new OverWatch(bag.iPortOrder, bag.SessionAcquisitionSavingDirectory);
....
private void OverWatcherControl(boolean checker)
{
if(checker)
EW.start();
else
EW.interrupt();
}
由于变量 bag.numberofDataToAcquire(公共整数类型)应该在用户需要时更改,我认为我必须停止此线程并更改变量然后再次运行此线程。我错了吗?或者我怎样才能中断这个线程?
谢谢,
【问题讨论】:
-
当这段代码“包含在一个while循环中”时究竟会发生什么?
-
无法中断线程,也看不到“线程已死..”的消息
-
您是否为 server.accept 设置了超时?如果没有,它将一直等到它得到数据包;这可能是你的问题。
-
仅供参考:我已经编辑了我的答案,以展示您如何使用
ServerSocketChannel来接受因调用thread.interrupt()而被打断的问题。
标签: java multithreading interrupt