2012-10-25 68 views

回答

6

這些是不同的實例相同類型,絕對不一樣的線程,你可以這樣做。

這個符號可以使它更清楚爲什麼(雖然它是相當於從輸出線分開原件):

Thread instance1 = new MyThread(0); //created one instance 
Thread instance2 = new MyThread(1); //created another instance 

//we have two different instances now 
// let's see if that is true, or not: 
System.out.println("The two threads are " + (instance1==instance2?"the same":"different")); 

instance1.start(); //start first thread instance 
instance2.start(); //start second instance 

//we just started the two different threads 

不過,根據MyThread實施,這威力帶來問題。多線程編程並非易事。線程實例應該以線程安全的方式運行,這對保證並不重要。

推薦閱讀:Java Concurrency In Practice (Peierls, Bloch, Bowbeer, Holmes, Lea)

+1

打我回答:) –

+0

只需幾秒鐘...人們圍繞着Java主題快速... – ppeterka

+0

@ppeterka大多數時間它*低掛果*。很多代表很少費力。 – maba

1

是的,因爲你實例化兩個線程。

儘管它們具有相同的類(MyThread),但每次在java中使用new關鍵字時,都會實例化一個新對象。這個新對象不能與原始對象共享數據。您已創建兩個單獨的MyThread對象;你可以啓動一個而不是另一個,或者啓動兩者。

+0

你的意思是他們不是一回事? –

3

由於the documentation說,你不能多次啓動一個線程 - 如果你在已經啓動的線程上調用start(),你會得到一個IllegalThreadStateException

但是,你的代碼不會做你說:你是不是開始同一線程兩次與代碼 - 你創建你啓動兩個獨立的MyThread對象。

相關問題