Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ThreadedStringBufferTest extends Thread {
- private static final String LINE_SEPARATOR = System.getProperty("line.separator");
- private static final StringBuffer sharedStringBuffer = new StringBuffer();
- private final String _name;
- private int _counter = 0;
- public ThreadedStringBufferTest(final String name) {
- _name = name;
- }
- public static void main(String[] args) {
- final String[] names = {"Able", "Bob", "Chris", "Don", "Ed"};
- final Thread[] threads = new Thread[names.length];
- for (int idx = 0; idx < names.length; ++idx) {
- threads[idx] = new ThreadedStringBufferTest(names[idx]);
- }
- final boolean threading = true; // Set 'true' for the real test.
- if (threading) {
- // This is the multi-threaded path through the program:
- for (Thread thread : threads) {
- thread.start();
- }
- for (Thread thread : threads) {
- try {
- thread.join();
- } catch (InterruptedException ex) {
- // "carelessly" discard the exception here
- }
- }
- } else {
- // This is single-threaded, for comparison:
- for (Thread thread : threads) {
- thread.run();
- }
- }
- System.out.println("Final Result:");
- System.out.println(sharedStringBuffer.toString());
- System.out.println("[end]");
- }
- @Override
- public void run() {
- for (int counter = 1; counter <= 5; ++ counter) {
- sharedStringBuffer.append("Hello World!")
- .append(" For my friend ").append(_name).append(" in particular.")
- .append(" This is message #").append(++_counter).append('.')
- .append(LINE_SEPARATOR);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement