Unterschied zwischen StringBuilder und StringBuffer

... komplette Frage anzeigen

3 Antworten

Hier noch ein Beispiel, dass die Unterschiede aufzeigt:

package TestsMA;import java.util.Random;class C1{ public static void main(String[] args) { try { for (int i = 0; i < 1000; i++) { testSyncString(); } } catch (Exception ex) { System.out.println(ex); } } /** * Unterschied zwischen StringBuilder und StringBuffer * * Nur Beim StringBuilder kommt es zu Unregelmäßigkeiten bis hin * zu Abstürzen. */ private static void testSyncString() throws Exception { StringBuilder sb1 = new StringBuilder(""); Thread th = new Thread(new C2(sb1,1)); Thread th2 = new Thread(new C2(sb1,2)); th.start(); th2.start(); sb1.append("caller;"); th.join(); th2.join(); String str = sb1.toString(); if (str.split(";").length < 5) System.out.println("ERROR 1 ==> "+sb1); StringBuffer sb2 = new StringBuffer(""); th = new Thread(new C3(sb2,1)); th2 = new Thread(new C3(sb2,2)); th.start(); th2.start(); sb2.append("caller;"); th.join(); th2.join(); str = sb2.toString(); if (str.split(";").length < 5) System.out.println("ERROR 2 ==> "+sb2); }}

class C2 implements Runnable{ StringBuilder sb; int nr; public C2(StringBuilder sb, int nr) { this.sb = sb; this.nr=nr; } @Override public void run() { sb.append(nr+"threat-start;"); String s =""; Random r = new Random(); for (int i = 0; i < r.nextInt(100000); i++) { s += i; } sb.append(nr+"threat-end;"); }}

class C3 implements Runnable{ StringBuffer sb; int nr; public C3(StringBuffer sb, int nr) { this.sb = sb; this.nr=nr; } @Override public void run() { sb.append(nr+"threat-start;"); String s =""; Random r = new Random(); for (int i = 0; i < r.nextInt(100000); i++) { s += i; } sb.append(nr+"threat-end;"); }}

Antwort bewerten Vielen Dank für Deine Bewertung

Was möchtest Du wissen?