如何杀死正在等待Java中的函数调用的线程? [英] how to kill a thread which is waiting for blocking function call in Java?

查看:440
本文介绍了如何杀死正在等待Java中的函数调用的线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程:

Thread t = new Thread(){
    public void run(){
        ServerSocketConnection scn = (ServerSocketConnection)
                Connector.open("socket://:1234");
        // Wait for a connection.
        SocketConnection sc = (SocketConnection) scn.acceptAndOpen();
       //do other operation
    }
};
t.start();

让我们说没有客户端正在连接到服务器,因此该线程将被阻止.现在我要杀死上述线程吗?我该如何杀死它?

Lets say no client is connecting to the Server, so this thread will be blocked.Now I want to kill the above thread t? How can I kill it?

推荐答案

Thread.interrupt()中断套接字上阻塞的线程.您可以尝试调用Thread.stop()Thread.destroy(),但是不建议使用这些方法(在J2ME中实际上是编辑 ),由于某些原因,您可以阅读此处.正如该文章所提到的,您所遇到的最佳解决方案是关闭您要阻塞的套接字:

Thread.interrupt() will not interrupt a thread blocked on a socket. You can try to call Thread.stop() or Thread.destroy(), but these methods are deprecated (edit: actually, absent in J2ME) and in some cases non-functional, for reasons you can read about here. As that article mentions, the best solution in your case is to close the socket that you're blocking on:

在某些情况下,您可以使用特定于应用程序的技巧.例如,如果某个线程正在一个已知的套接字上等待,则可以关闭该套接字以使该线程立即返回.不幸的是,实际上没有任何一种技术可以正常工作.应该注意的是,在所有等待线程不响应Thread.interrupt的情况下,它也不响应Thread.stop.此类情况包括故意的拒绝服务攻击,以及thread.stop和thread.interrupt无法正常工作的I/O操作.

In some cases, you can use application specific tricks. For example, if a thread is waiting on a known socket, you can close the socket to cause the thread to return immediately. Unfortunately, there really isn't any technique that works in general. It should be noted that in all situations where a waiting thread doesn't respond to Thread.interrupt, it wouldn't respond to Thread.stop either. Such cases include deliberate denial-of-service attacks, and I/O operations for which thread.stop and thread.interrupt do not work properly.

这篇关于如何杀死正在等待Java中的函数调用的线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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