Advertisement
Guest User

Untitled

a guest
Jan 24th, 2015
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. import java.util.Random;
  2.  
  3. public class StringBufferVsSringBuilder {
  4. public static int demo(final Object stringJoiner, final int testCount) throws InterruptedException {
  5. ThreadGroup group = new ThreadGroup(stringJoiner.getClass().getName() + "@" + stringJoiner.hashCode());
  6. final Random rand = new Random();
  7.  
  8. Runnable listAppender = new Runnable() {
  9. public void run() {
  10. try {
  11. Thread.sleep(rand.nextInt(2));
  12. } catch (InterruptedException e) {
  13. return;
  14. }
  15. if (stringJoiner instanceof StringBuffer) {
  16. ((StringBuffer)stringJoiner).append("0");
  17. } else if (stringJoiner instanceof StringBuilder) {
  18. ((StringBuilder)stringJoiner).append("0");
  19. }
  20. }
  21. };
  22.  
  23. for (int i = 0; i < testCount; i++) {
  24. new Thread(group, listAppender, "InsertList-" + i).start();
  25. }
  26.  
  27. while (group.activeCount() > 0) {
  28. Thread.sleep(10);
  29. }
  30.  
  31. return stringJoiner.toString().length();
  32. }
  33.  
  34. public static void main(String[] args) throws InterruptedException {
  35. StringBuilder stringBuilder = new StringBuilder();
  36. StringBuffer stringBuffer = new StringBuffer();
  37. final int N = 10000;
  38. for (int i = 0; i < 10; i++) {
  39. stringBuilder.delete(0, stringBuilder.length());
  40. stringBuffer.delete(0, stringBuffer.length());
  41. int builderLength = demo(stringBuilder, N);
  42. int bufferLength = demo(stringBuffer, N);
  43. System.out.println("StringBuilder/StringBuffer: " + builderLength + "/" + bufferLength);
  44. }
  45. }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement