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

查看:112
本文介绍了我怎么能杀死一个线程?不使用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实例变量引用错误的线程时出现错误) ,线程#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 的目的是测试中断标志的状态然后清除它,这是抛出 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天全站免登陆