线程如何在Java中关闭? [英] How a thread should close itself in Java?

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

问题描述

这是一个简短的问题。在某些时候,我的线程理解它应该自杀。最好的方法是:

This is a short question. At some point my thread understand that it should suicide. What is the best way to do it:


  1. Thread.currentThread()。interrupt();

  2. return;

顺便说一句,为什么在第一种情况下我们需要使用 currentThread ?是线程不引用当前线程?

By the way, why in the first case we need to use currentThread? Is Thread does not refer to the current thread?

推荐答案

如果你想要终止线程,然后返回就好了。你不需要调用 Thread.currentThread()。interrupt()(它不会做任何坏事。只是你不需要。)这是因为 interrupt()主要用于通知线程的所有者(好吧,不是100%准确,而是排序)。因为您是该线程的所有者,并且您决定终止该线程,所以没有人可以通知,因此您无需调用它。

If you want to terminate the thread, then just returning is fine. You do NOT need to call Thread.currentThread().interrupt() (it will not do anything bad though. It's just that you don't need to.) This is because interrupt() is basically used to notify the owner of the thread (well, not 100% accurate, but sort of). Because you are the owner of the thread, and you decided to terminate the thread, there is no one to notify, so you don't need to call it.


顺便说一下,为什么在第一种情况下我们
需要使用currentThread?线程
是不是指当前线程?

By the way, why in the first case we need to use currentThread? Is Thread does not refer to the current thread?

是的,它没有。我想这可能会令人困惑,例如Thread.sleep()影响当前线程,但Thread.sleep()是一个静态方法。

Yes, it doesn't. I guess it can be confusing because e.g. Thread.sleep() affects the current thread, but Thread.sleep() is a static method.

如果你不是线程的所有者(例如,如果你有未扩展线程并编码 Runnable 等)你应该这样做

If you are NOT the owner of the thread (e.g. if you have not extended Thread and coded a Runnable etc.) you should do

Thread.currentThread().interrupt();
return;

这样,无论调用runnable的代码都知道线程被中断=(通常)应该停止无论它做什么并终止。正如我之前所说,它只是一种沟通机制。所有者可能只是忽略中断状态而什么也不做。但是如果你设置了中断状态,将来有人可能会感谢你。

This way, whatever code that called your runnable will know the thread is interrupted = (normally) should stop whatever it is doing and terminate. As I said earlier, it is just a mechanism of communication though. The owner might simply ignore the interrupted status and do nothing.. but if you do set the interrupted status, somebody might thank you for that in the future.

出于同样的原因,你永远不应该这样做

For the same reason, you should never do

Catch(InterruptedException ie){
     //ignore
}

因为如果你这样做,你正在那里停止消息。相反应该做

Because if you do, you are stopping the message there. Instead one should do

Catch(InterruptedException ie){
    Thread.currentThread().interrupt();//preserve the message
    return;//Stop doing whatever I am doing and terminate
}

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

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