關於 Thread.currentThread()

currentThread()  究竟是什麼? 其實currentThread() 只是Thread 的一個靜態方法。返回的正是執行當前代碼指令的線程引用: java

    /**
     * Returns a reference to the currently executing thread object.
     *
     * @return  the currently executing thread.
     */
    public static native Thread currentThread();

換句話說, Thread.currentThread() 返回的是 一個實例。 只不過呢, 這個實例確實比較特殊。 這個實例是當前Thread 的引用。Thread.currentThread() 固然 不等於 Thread。 程序員

 

問題1 :編程

以前一直存在的一個問題是:less

Thread.currentThread().sleep(x) 工具

Thread.sleep(x)post

二者到底有什麼區別,Thread.currentThread() 這樣的寫法是必須的嗎。 到底哪一種寫法更好呢? this

那爲何咱們有經常看到: spa

Thread.currentThread().sleep(2000);

這樣的用法呢??.net

 

其實,若是咱們代碼這麼寫: 線程

Thread.currentThread().sleep(2000);

會有下面的提示, 固然這個提示也不算是什麼錯誤。可是總歸是不太好的。由於這個提示有點警告的意味。

Static member 'java.lang.Thread.sleep(long)' accessed via instance reference less... (Ctrl+F1)
Shows references to static methods and fields via class instance rather than a class itself.

 

它 的意思是說, 你正在經過一個對象實例來調用它的靜態方法。 (通常來講, 這確實是很差的編程實踐。)

可是改爲下面這樣就行了:
Thread.sleep(2000);

 

可是,當年,我看視頻看別人代碼,都是這麼寫的。 事實上,雖然二者效果徹底同樣,都沒錯,可是仍是細微差異的。那麼,哪一個是最佳實踐呢? 答案是後者: Thread.sleep(x) 

 

本質上來說, 實際上是沒有區別的,其功效徹底同樣。不過呢, 一些代碼檢查工具會認爲  前者有點問題。

While you can call a static method via an instance reference, it's not good style ———— 這個就是代碼檢查工具提示判斷的 依據。 不是一個好的 style。

Thread.currentThread().sleep(2000); 這樣 就可讓這行代碼看起來 達到了某些程序員的「本來的心意」。 雖然這樣作是無益的,可是也是無害的。 總之,它能夠避免某些問題,能夠避免某些程序員出現低級錯誤。。。  這個實際上是早期程序員的一個通用的寫法, 無益也無害。 已經成爲了一個不那麼好的習俗了吧

 

 

In Java, sleep is a static method. Both your examples do exactly the same thing, but the former version is confusing because it looks like it is calling a method on a specific object but it's not doing that at all. In your example it won't matter much, but it is more dangerous if you have the following:

someOtherThread.sleep(x);

This time it looks like you are telling some other thread to sleep, but in fact you are putting the current thread to sleep. The way to avoid making this type of mistake is to always call static methods using the class rather than a specific object.

 

 

The way to avoid making this type of mistake is to always call static methods using the class rather than a specific object. —— 避免了「調用一個實例的靜態方法,而實際上應該是調用一個類的靜態方法」 之類的錯誤。 其實說白了也就是避免這樣的錯誤:   someOtherThread.sleep(x);

 

問題2:

還有一個問題是: Thread.currentThread()與this的區別

在線程的run 方法內部, Thread.currentThread()與this 實際上是一個意思(除非你手動執行run方法,而不是經過啓動線程的方式)。 不過呢, 其餘的某些方法或場合,卻可能出現不一致。

通常來講,Thread.currentThread() 用於不方便使用this 的場合。 Thread.currentThread() 明確代表了它所針對的對象是 當前線程! 不是this! 固然,若是碰巧this 就是當前線程, 那也是沒毛病的。

 

 

參考:

http://blog.csdn.net/yezis/article/details/57513130

https://stackoverflow.com/questions/2077216/java-thread-currentthread-sleepx-vs-thread-sleepx

相關文章
相關標籤/搜索