2016-11-29 81 views
-1
class MyRunnable implements Runnable 
{ 
    MyRunnable(String name) 
    { 
     new Thread(this, name).start(); 
    } 
    public void run() 
    { 
     System.out.println("run() called by " + Thread.currentThread().getName()); 
     System.out.println(Thread.currentThread().getName()); 
    } 
} 
public class TestClass 
{ 
    public static void main(String[] args) 
    { 
     System.out.println(Thread.currentThread().getName()); 
     Thread.currentThread().setName("First"); 
     MyRunnable mr = new MyRunnable("MyRunnable"); 
     mr.run(); 
     Thread.currentThread().setName("Second"); 
     mr.run(); 
    } 
} 

輸出將是 主, 首先, 其次, MyRunnableThread.currentThread()。setName()調用線程的run方法嗎?

爲什麼到Thread.currentThread()的調用的setName( 「第一」)。調用run()方法?

+3

是什麼讓你覺得它呢? – Paul

+4

'new Thread(this,name).start();'在ctor中?不不不**。永遠不要這樣做。甚至不是一個笑話。 –

+2

你正在處理競爭條件。 – nhaarman

回答

2

它沒有。你正在觀察的是race condition。僅僅因爲您在MyRunnable構造函數中啓動了新的Thread,並不意味着它將在您的main()方法中的mr.run()調用之前執行。與開始線程有關的開銷,這需要時間。如果您將Thread.sleep()插入main()方法中,則輸出將會改變。

相關問題