具有套接字I / O阻塞操作的中断/停止线程 [英] Interrupt/stop thread with socket I/O blocking operation

查看:226
本文介绍了具有套接字I / O阻塞操作的中断/停止线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的服务器应用程序的某个时刻,我想停止一些执行I / O阻塞操作的线程。

At some point of my server application I want to stop some threads that are performing I/O blocking operations.

例如,其中一个有以下 run()方法:

For instance, one of them have the following run() method:

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);
        }
    }
}

如果我想停止运行此代码的线程,我该怎么办?

If I Want to stop a thread running this code, what should I do?

这里他们展示了如何做(如何停止等待很长时间的线程(例如,输入)?),但我不明白他们的意思:

Here they show how to do (How do I stop a thread that waits for long periods (e.g., for input)?), but I don't understand what they mean with:


要使这项技术有效,抓住
的任何方法都至关重要一个中断异常,并没有准备立即处理它
重新确认异常。我们说重新声明而不是重新抛出,
因为并不总是可以重新抛出异常。如果没有声明捕获InterruptedException的
方法抛出
这个(已检查)异常,那么它应该用咒语后的
重新中断:Thread.currentThread()。interrupt( );

For this technique to work, it's critical that any method that catches an interrupt exception and is not prepared to deal with it immediately reasserts the exception. We say reasserts rather than rethrows, because it is not always possible to rethrow the exception. If the method that catches the InterruptedException is not declared to throw this (checked) exception, then it should "reinterrupt itself" with the following incantation: Thread.currentThread().interrupt();

任何人都可以给我一些提示吗?一些代码示例将非常受欢迎。

Can anyone give me some hints? Some code examples would be very appreciated.

推荐答案

一个解决方案,由Peter Lawrey描述,也见过在哪里关闭套接字。

A solution, described by Peter Lawrey and also seen here is to close the socket.

使用nio,您还可以使用 SocketChannel 可中断并允许应用 Java的标准中断模型

With nio, You could also use a SocketChannel which is interruptible and would allow the application of the standard interrupt model of Java.

调用中断 Thread对象的方法会抛出InterruptedException,这会阻止你的阻塞IO操作。

A call to the interrupt method of your Thread object would throw an InterruptedException which would stop even your blocking IO operation.

这篇关于具有套接字I / O阻塞操作的中断/停止线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆