2013-10-09 30 views
0

我想知道StringBuilder & StringBuffer類與他們實際使用的區別。所以,我寫了2個代碼片段,其中我使用StringBuilder & StringBuffer對象同時產生3個線程。爲什麼StringBuilder訪問似乎是同步的?

當我運行代碼時,我希望所有3個線程在StringBuilder的情況下同步運行,以StringBuffer的情況以同步的方式運行。但是在這兩種情況下,它們都以同步方式運行。 那麼StringBuffer類有什麼用?:confused:

(在String對象的情況下,所有3個線程同時運行)。我將分享代碼片段供您參考。如果我在理解多線程本身的概念方面錯誤,也請糾正我。並請更正代碼。

// StringBuilder... 

public class MultiTread implements Runnable{ 
private StringBuilder name; 
public MultiTread(StringBuilder string){ 
name=string; 
} 

public void run(){ 
for(int i=0; i<=10; i++){ 
System.out.println(name.append(i)); 
} 
} 
public static void main(String[] args){ 
Thread th = new Thread(new MultiTread(new StringBuilder("thread1:"))); 
Thread th1 = new Thread(new MultiTread(new StringBuilder("thread2:"))); 
Thread th2 = new Thread(new MultiTread(new StringBuilder("thread3:"))); 

th.start(); 
th1.start(); 
th2.start(); 
} 
} 

.................. 

//StringBuffer... 

public class MultiTreadBuf implements Runnable{ 
private StringBuffer name; 
public MultiTreadBuf(StringBuffer string){ 
name=string; 
} 

public void run(){ 
for(int i=0; i<=10; i++){ 
System.out.println(name.append(i)); 
} 
} 
public static void main(String[] args){ 
Thread th = new Thread(new MultiTreadBuf(new StringBuffer("thread1:"))); 
Thread th1 = new Thread(new MultiTreadBuf(new StringBuffer("thread2:"))); 
Thread th2 = new Thread(new MultiTreadBuf(new StringBuffer("thread3:"))); 

th.start(); 
th1.start(); 
th2.start(); 
} 
} 

........ 

//String.... 

public class MuiltiTreadStr implements Runnable{ 
private String name; 
public MuiltiTreadStr(String string){ 
name=string; 
} 

public void run(){ 
for(int i=0; i<=10; i++){ 
System.out.println(name+i); 
} 
} 
public static void main(String[] args){ 
System.out.println("main begins..."); 
Thread th = new Thread(new MuiltiTreadStr("thread1:")); 
Thread th1 = new Thread(new MuiltiTreadStr("thread2:")); 
Thread th2 = new Thread(new MuiltiTreadStr("thread3:")); 
System.out.println("spawning 3 threads..."); 
th.start(); 
th1.start(); 
th2.start(); 
System.out.println("main ends..."); 
} 
} 
+0

谷歌,第一個結果是:http://stackoverflow.com/questions/355089/stringbuilder-and-stringbuffer-in-java – Enigma

回答

7

您正在爲每個線程使用不同的StringBuffers和StringBuilders實例。要查看同步,您必須在所有線程中使用相同的對象實例;-)

+0

實際上,OP代碼測試的唯一線程行爲是'System.out.println ()' - 其他的東西都在自己的線程中運行。 – dimo414

0

您應該已經爲所有線程使用了相同的StringBuilder/StingBuffer實例。以便您可以看到同步。

2

對預期行爲和實際行爲的描述會有幫助,但我猜測你看到了每個線程的順序輸出,但預計會看到不同線程的交錯輸出。

線程調度取決於系統。不能保證線程將被公平地調度(例如,獲得「時間片」的同等優先級的線程),或者即使在多處理器系統上線程也將併發運行。

此外,請記住System.out.println()已同步,並且不保證內部鎖的爭用能夠公平地或立即解決。所以有可能一個線程重複獲取System.out上的鎖,其他線程在該線程完成之前沒有機會打印。您可以使用java.util.concurrent.ReentrantLock獲得「公平」鎖定(可能會損害性能)。

另一種可能性是,您的系統速度如此之快,以至於一個線程在下一個線程嘗試開始運行之前完成。更多的迭代將有助於檢測這種情況。

+0

+1。 'System.out.println()是同步的',甚至沒有想過。很好的解釋 –

相關問題