Advertisement
JeffGrigg

ThreadedStringBufferTest

Sep 3rd, 2017
316
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.90 KB | None | 0 0
  1. public class ThreadedStringBufferTest extends Thread {
  2.  
  3.     private static final String LINE_SEPARATOR = System.getProperty("line.separator");
  4.     private static final StringBuffer sharedStringBuffer = new StringBuffer();
  5.  
  6.     private final String _name;
  7.     private int _counter = 0;
  8.  
  9.     public ThreadedStringBufferTest(final String name) {
  10.         _name = name;
  11.     }
  12.  
  13.     public static void main(String[] args) {
  14.         final String[] names = {"Able", "Bob", "Chris", "Don", "Ed"};
  15.         final Thread[] threads = new Thread[names.length];
  16.         for (int idx = 0; idx < names.length; ++idx) {
  17.             threads[idx] = new ThreadedStringBufferTest(names[idx]);
  18.         }
  19.  
  20.         final boolean threading = true;  // Set 'true' for the real test.
  21.  
  22.         if (threading) {
  23.             // This is the multi-threaded path through the program:
  24.             for (Thread thread : threads) {
  25.                 thread.start();
  26.             }
  27.             for (Thread thread : threads) {
  28.                 try {
  29.                     thread.join();
  30.                 } catch (InterruptedException ex) {
  31.                     // "carelessly" discard the exception here
  32.                 }
  33.             }
  34.         } else {
  35.             // This is single-threaded, for comparison:
  36.             for (Thread thread : threads) {
  37.                 thread.run();
  38.             }
  39.         }
  40.  
  41.         System.out.println("Final Result:");
  42.         System.out.println(sharedStringBuffer.toString());
  43.         System.out.println("[end]");
  44.     }
  45.  
  46.     @Override
  47.     public void run() {
  48.         for (int counter = 1; counter <= 5; ++ counter) {
  49.             sharedStringBuffer.append("Hello World!")
  50.                     .append("  For my friend ").append(_name).append(" in particular.")
  51.                     .append("  This is message #").append(++_counter).append('.')
  52.                     .append(LINE_SEPARATOR);
  53.         }
  54.     }
  55.  
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement