java Thread.currentThread().getName() 和 getName() 有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10231354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the difference between Thread.currentThread().getName() and getName()?
提问by suisuisui
What's the difference between the static Thread.currentThread().getName()
and getName()
of a particular Thread instance?
静态Thread.currentThread().getName()
和getName()
特定 Thread 实例的区别是什么?
回答by Chris Blades
The difference is getName()
is an instance method, meaning it operates on an instance of the Thread
class.
区别在于getName()
实例方法,这意味着它对Thread
类的实例进行操作。
Thread.getCurrentThread()
is a class or static method, meaning it does not operate on an instance of Thread
but rather on its class.
Thread.getCurrentThread()
是一个类或静态方法,这意味着它不操作实例Thread
而是操作它的类。
The ultimate difference is this: if you call Thread.currentThread().getName()
, currentThread()
will return an instance of Thread
, which you can then call getName()
on that instance. You cannot call Thread.getName()
because getName()
has to be called on an instance of Thread
.
最终的区别在于:如果您调用Thread.currentThread().getName()
,currentThread()
将返回 的实例Thread
,然后您可以getName()
在该实例上调用该实例。您不能调用,Thread.getName()
因为getName()
必须在 的实例上调用Thread
。
回答by László Báthory
However, very much to the contrary, Thread.currentThread() returns the current Thread instance. Therefore the answer is: The two funcions are the same from the same thread. Try this one:
然而,恰恰相反, Thread.currentThread() 返回当前 Thread 实例。因此答案是:来自同一个线程的两个函数是相同的。试试这个:
Thread nuThread = new Thread("Proba"){
@Override
public void run() {
System.out.println(this.getName());
Thread other = Thread.currentThread();
System.out.println(other.getName());
System.out.println(this==other ? "Same object":"Different object");
}
};
nuThread.start();
try {
nuThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}