use*_*761 4 java multithreading interrupt
我试图关闭当前线程,它是多线程服务器的一部分.线程已准备好打开客户端可以访问的套接字.
除非下面的代码包含在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");
}
}
Run Code Online (Sandbox Code Playgroud)
这是GUI事件的一部分:这在没有"new ServerThread ..."代码的情况下运行良好.
private OverWatch EW = new OverWatch(bag.iPortOrder, bag.SessionAcquisitionSavingDirectory);
....
private void OverWatcherControl(boolean checker)
{
if(checker)
EW.start();
else
EW.interrupt();
}
Run Code Online (Sandbox Code Playgroud)
由于变量bag.numberofDataToAcquire(公共整数类型)应该在用户需要时更改,我想我必须停止此线程并更改变量然后再次运行此线程.我错了吗?或者我该如何中断这个帖子?
谢谢,
Mik*_*ark 11
ServerSocket.accept()是一个阻塞调用,它不响应线程中断.几乎所有的java.net阻塞调用(连接,读取,接受等)都不响应Thread.interrupt().此行为是"按设计".
唤醒被阻塞的线程.accept()或.read()关闭底层套接字的方法.
或者,您可以setSoTimeout在ServerSocket上设置SO_TIMEOUT(),这将导致.accept()通过抛出a来定期唤醒SocketTimeoutException.您可以捕获该异常并将其用作检查线程上的中断状态的机会.
该java.nio软件包(Java 1.4+)提供了一个备用套接字API,可以更好地响应中断.
小智 6
作为使用超时或杀死套接字的替代方法:
伪造与插座的新连接.这将"唤醒" accept()然后可以使用另外的信令机制(例如标志或中断检查)(尽管逻辑必须从显示略微改变而不是"谎言" println).
我之前使用过这种方法并且运行良好:无需等待超时(甚至是排序)或处理另一个异常并且套接字保持打开/有效(可能需要也可能不需要).另一方面,我不确定在一次真正长时间/破坏的 TCP握手会发生什么,但这是我从未遇到的情况;-)
快乐的编码.
| 归档时间: |
|
| 查看次数: |
3514 次 |
| 最近记录: |