我怎样才能杀死一个线程?不使用 stop(); [英] How can I kill a thread? without using stop();

查看:32
本文介绍了我怎样才能杀死一个线程?不使用 stop();的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Thread currentThread=Thread.currentThread();
        public void run()
        {               

             while(!shutdown)
            {                               
                try
                {
                    System.out.println(currentThread.isAlive());
                Thread.interrupted();

                System.out.println(currentThread.isAlive());
                if(currentThread.isAlive()==false)
                {
                    shutdown=true;
                }
                }
                catch(Exception e)
                {
                    currentThread.interrupt();
                }                   
            }
        }

    });
    thread.start();

推荐答案

调用 stop 的替代方法是使用中断向线程发出信号,表明您希望它完成正在执行的操作.(这假设您要停止的线程表现良好,如果它在抛出 InterruptedExceptions 后立即处理它们而忽略它们,并且不检查中断状态,那么您将重新使用 stop().)

The alternative to calling stop is to use interrupt to signal to the thread that you want it to finish what it's doing. (This assumes the thread you want to stop is well-behaved, if it ignores InterruptedExceptions by eating them immediately after they are thrown and doesn't check the interrupted status then you are back to using stop().)

这是我写的一些代码作为线程问题的答案 此处,这是线程中断工作原理的示例:

Here's some code I wrote as an answer to a threading question here, it's an example of how thread interruption works:

public class HelloWorld {

    public static void main(String[] args) throws Exception {
        Thread thread = new Thread(new Runnable() {

            public void run() {
                try {
                    while (!Thread.currentThread().isInterrupted()) {
                        Thread.sleep(5000);
                        System.out.println("Hello World!");
                    }
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        });
        thread.start();
        System.out.println("press enter to quit");
        System.in.read();
        thread.interrupt();
    }
}

需要注意的一些事项:

  • 中断会导致 sleep()wait() 立即抛出,否则你会卡在等待睡眠时间过去.

  • Interrupting causes sleep() and wait() to immediately throw, otherwise you are stuck waiting for the sleep time to pass.

请注意,不需要单独的布尔标志.

Note that there is no need for a separate boolean flag.

被停止的线程通过检查中断状态并在while循环外捕获InterruptedExceptions(使用它退出循环)来协作.中断是一个可以使用异常进行流量控制的地方,这就是它的全部意义所在.

The thread being stopped cooperates by checking the interrupted status and catching InterruptedExceptions outside the while loop (using it to exit the loop). Interruption is one place where it's ok to use an exception for flow control, that is the whole point of it.

在 catch 块中的当前线程上设置中断在技术上是最佳实践,但对于本示例来说太过分了,因为没有其他东西需要设置中断标志.

Setting interrupt on the current thread in the catch block is technically best-practice but is overkill for this example, because there is nothing else that needs the interrupt flag set.

关于已发布代码的一些观察:

Some observations about the posted code:

  • 发布的示例不完整,但将当前线程的引用放在实例变量中似乎是个坏主意.它将被初始化为任何创建对象的线程,而不是执行 run 方法的线程.如果同一个 Runnable 实例在多个线程上执行,则实例变量在大多数情况下不会反映正确的线程.

  • The posted example is incomplete, but putting a reference to the current thread in an instance variable seems like a bad idea. It will get initialized to whatever thread is creating the object, not to the thread executing the run method. If the same Runnable instance is executed on more than one thread then the instance variable won't reflect the right thread most of the time.

检查线程是否处于活动状态必然总是会导致 true(除非存在错误,其中 currentThread 实例变量引用了错误的线程),Thread#isAlive 是仅在线程完成执行后才返回 false,它不会因为被中断而返回 false.

The check for whether the thread is alive is necessarily always going to result in true (unless there's an error where the currentThread instance variable is referencing the wrong thread), Thread#isAlive is false only after the thread has finished executing, it doesn't return false just because it's been interrupted.

调用 Thread#interrupted 将导致清除中断标志,在这里没有意义,特别是因为返回值被丢弃.调用Thread#interrupted的意义在于测试中断标志的状态然后清除它,这是抛出InterruptedException的东西使用的一个方便的方法.

Calling Thread#interrupted will result in clearing the interrupt flag, and makes no sense here, especially since the return value is discarded. The point of calling Thread#interrupted is to test the state of the interrupted flag and then clear it, it's a convenience method used by things that throw InterruptedException.

这篇关于我怎样才能杀死一个线程?不使用 stop();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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