1. 程式人生 > >關於 Thread.currentThread()

關於 Thread.currentThread()

som 技術 方法 tin dangerous lin text 本質 some

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

    /**
     * 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 :

之前一直存在的一個問題是:

Thread.currentThread().sleep(x)

Thread.sleep(x)

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

那為什麽我們有常常看到:

Thread.currentThread().sleep(2000);

這樣的用法呢??

其實,如果我們代碼這麽寫:

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); 這樣 就可以讓這行代碼看起來 達到了某些程序員的“原本的心意”。 雖然這樣做是無益的,但是也是無害的。 總之,它可以避免某些問題,可以避免某些程序員出現低級錯誤。。。 這個其實是早期程序員的一個通用的寫法, 無益也無害。 已經成為了一個不那麽好的習俗了吧

26down vote

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

關於 Thread.currentThread()