Java:Thread.interrupted()和Thread.isInterrupted()之间的使用差异? [英] Java: Difference in usage between Thread.interrupted() and Thread.isInterrupted()?

查看:93
本文介绍了Java:Thread.interrupted()和Thread.isInterrupted()之间的使用差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java问题:据我所知,有两种方法可以检查线程内部线程是否收到中​​断信号, Thread.interrupted() Thread.isInterrupted(),它们之间的唯一区别是前者重置内部中断标志。

Java question: As far as I know, there are two ways to check inside a thread whether the thread received an interrupt signal, Thread.interrupted() and Thread.isInterrupted(), and the only difference between them is that the former resets the internal interrupted flag.

到目前为止,我一直使用 Thread.isInterrupted(),从来没有遇到任何问题。然后,我见过的大多数教程都建议使用 Thread.interrupted()。有没有具体原因?

So far, I've always used Thread.isInterrupted() and never had any problems with it. Then again, most tutorials I've seen recommend using Thread.interrupted(). Is there any specific reason for that?

推荐答案

interrupted() static 并检查当前线程。 isInterrupted() 是一个实例方法,用于检查调用它的 Thread 对象。

interrupted() is static and checks the current thread. isInterrupted() is an instance method which checks the Thread object that it is called on.

常见错误是在实例上调用静态方法。

A common error is to call a static method on an instance.

Thread myThread = ...;
if (myThread.interrupted()) {} // WRONG! This might not be checking myThread.
if (myThread.isInterrupted()) {} // Right!

另一个区别是 interrupted()清除当前线程的状态。换句话说,如果你连续两次调用它并且线程没有在两次调用之间中断,那么第二次调用将返回 false ,即使第一次调用返回 true

Another difference is that interrupted() also clears the status of the current thread. In other words, if you call it twice in a row and the thread is not interrupted between the two calls, the second call will return false even if the first call returned true.

Javadocs 告诉你这样重要的事情;经常使用它们!

The Javadocs tell you important things like this; use them often!

这篇关于Java:Thread.interrupted()和Thread.isInterrupted()之间的使用差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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