Last active
December 15, 2019 04:19
-
-
Save imrexhuang/df799e10868fed6d7ec94a7129160691 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//https://coderanch.com/t/666742/java/understand-StringBuffer-thread-safe-StringBuilder | |
/* | |
* Demonstrate StringBuilder is not thread safe | |
*/ | |
public class StringBuilderWithMultThreadDemo implements Runnable { | |
StringBuilder strBuilder; | |
public StringBuilderWithMultThreadDemo() { | |
strBuilder = new StringBuilder(); | |
} | |
@Override | |
public void run() { | |
for (int i = 0; i < 50000; i++) { | |
//addChar(); ///non Thread-Safe | |
addCharTS(); //Thread-Safe | |
} | |
} | |
public void addChar() { | |
/* | |
* Here appended 6 A and removed 5 A at each call to this method. Total | |
* 1 A at each call Expected Accurate Total StringBuilder length = loops | |
* in run method * 1 i.e. 50000 * 1 for one thread Here we have 2 | |
* threads so = 100000 | |
*/ | |
try { | |
strBuilder.append("A"); | |
strBuilder.append("A"); | |
strBuilder.append("A"); | |
strBuilder.deleteCharAt(0); | |
strBuilder.append("A"); | |
strBuilder.append("A"); | |
strBuilder.append("A"); | |
for (int i = 0; i < 4; i++) { | |
strBuilder.deleteCharAt(0); | |
} | |
} catch (ArrayIndexOutOfBoundsException e) { | |
System.out.println("A wasn't at index 0 " + e.getMessage()); | |
} | |
} | |
public synchronized void addCharTS() { | |
/* | |
* Here appended 6 A and removed 5 A at each call to this method. Total | |
* 1 A at each call Expected Accurate Total StringBuilder length = loops | |
* in run method * 1 i.e. 50000 * 1 for one thread Here we have 2 | |
* threads so = 100000 | |
*/ | |
try { | |
strBuilder.append("A"); | |
strBuilder.append("A"); | |
strBuilder.append("A"); | |
strBuilder.deleteCharAt(0); | |
strBuilder.append("A"); | |
strBuilder.append("A"); | |
strBuilder.append("A"); | |
for (int i = 0; i < 4; i++) { | |
strBuilder.deleteCharAt(0); | |
} | |
} catch (ArrayIndexOutOfBoundsException e) { | |
System.out.println("A wasn't at index 0 " + e.getMessage()); | |
} | |
} | |
public static void main(String[] args) { | |
StringBuilderWithMultThreadDemo strBldrWthThrdDmobj1 = new StringBuilderWithMultThreadDemo(); | |
Thread threadOne = new Thread(strBldrWthThrdDmobj1, "Thread One"); | |
Thread threadTwo = new Thread(strBldrWthThrdDmobj1, "Thread Two"); | |
threadOne.start(); | |
threadTwo.start(); | |
try { | |
threadOne.join(); | |
threadTwo.join(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
System.out.println("Final StringBuilder Length: " + strBldrWthThrdDmobj1.strBuilder.length()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment