我怎么能在一个线程中停止块方法DatagramSocket.receive() [英] how can i stop the block method DatagramSocket.receive() in a thread

查看:1034
本文介绍了我怎么能在一个线程中停止块方法DatagramSocket.receive()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在主线程中创建一个 DatagramSocket ,然后创建一个内部类线程来监听端口。当我在主线程中关闭 DatagramSocket 时,它总是遇到错误套接字关闭,因为在内部类线程中我调用了 receive()方法,它阻止了内部类线程。这是内部类的代码:

i create a DatagramSocket in the main thread,and then create a inner class thread to listen the port. when i close the DatagramSocket in the main thread, it always came across an error socket closed because in the inner class thread i called the receive() method,and it blocked the inner class thread. here is the code of the inner class:

class ReceiveText extends Thread
{
    @Override
    public void run()
    {
        while(true)
        {
            byte[] buffer = new byte[1024];
            DatagramPacket dp = new DatagramPacket(buffer, buffer.length);
            try {
                udpSocket.receive(dp);//blocked here
                byte[] data = dp.getData();
                String message = new String(data, 0 , dp.getLength());
                setTxtAreaShowMessage(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

i想要在关闭DatagramSocket之前停止内部类线程,但不建议使用 stop()方法。我怎么能这样做?

i want to stop the inner class thread before close the DatagramSocket, but the stop() method is not recommended. how can i do that?

推荐答案

关闭套接字,这将阻止来自阻塞的receive()调用。如果首先设置一个关闭标志,那么在catch(IOException)块中,如果设置了标志,则可以安全地忽略该异常。 (你可能也可以在DatagramSocket上使用isClosed()方法而不是标志)

Close the socket, which will stop the receive() call from blocking. If you first set a closed flag then in the catch (IOException) block you can safely ignore the exception if the flag is set. (You could probably also use isClosed() method on DatagramSocket instead of a flag)

这篇关于我怎么能在一个线程中停止块方法DatagramSocket.receive()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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