---
title: "StringBuffer类及线程运行测试"
author: "BlueCore"
date: "2009-10-12T09:37:40Z"
tags: []
slug: "stringbuffer"
draft: false
lastmod: "2009-10-17T13:12:19Z"
id: 485733
url: "https://bluecore.iteye.com/blog/485733"
---

虽然平时常常看到，毕竟很少用。居然在笔试的时候碰到了，而且还写得不好，真是惭愧...

StringBuffer类，主要是insert（int，String/int/Object/...）与append（String/int/Object/...）两个方法；
最后用.toString（）方法把缓冲区内的数据转换为字符串表示。

StringBuffer类的引用：http://www.leftworld.net/online/j2sedoc/javaref/java.lang.stringbuffer_dsc.htm

据说是线程安全的，不过测试了下，发现这个概念理解有出入，貌似每次的结果是有差别的。


```java

public class A {

    public static StringBuffer bf=new StringBuffer();
    /**
     * @param args
     */
    public static void main(String[] args) {

        Thread a= new threadA();
        Thread b= new threadB();
        
        a.start();
        b.start();

        //System.out.println(A.bf.toString());
    }
}   

    class threadA extends Thread{
        public void run(){
            for(int i=1;i<=10;i++){
                A.bf.append(1);
                try {
                    sleep(10);
                } catch (InterruptedException e) {
                   continue;
                }
            }

            System.out.println(A.bf.toString());
        }
    }
    
    class threadB extends Thread{
        public void run(){
            for(int i=1;i<=10;i++){
                A.bf.append(2);
                try {
                    sleep(10);
                } catch (InterruptedException e) {
                    continue;
                }
            }

            System.out.println(A.bf.toString());
        }
    }

```


而且还发现了一个问题，若是用wait（）来代替sleep（）运行时报异常java.lang.IllegalMonitorStateException: current thread not owner，因为wait()方法会导致线程放弃对象锁，而该对象没有加锁。

还有一个问题，就是不知道如何在main函数中判断子线程的终止以打印最终结果。晚上回去研究下好了。

下面附阿润写的一个，使用回调函数来传递结果的例子。其实用join()方法就OK了。不过这里主要是为了看下回调函数，有点锁的感觉。


```java

public class A {

	public static StringBuffer bf = new StringBuffer();

	public static int threadCount;

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		Thread a = new threadA();
		Thread b = new threadB();

		threadCount = 2;

		a.start();
		b.start();

		// System.out.println(A.bf.toString());
	}

	/**
	 * Each User's Thread call this method at the end of run()
	 */
	public static synchronized void callback() {
		--threadCount;
		if (threadCount <= 0) {
			System.out.println("Final Result: ");
			System.out.println(A.bf.toString());
			System.out.println("Program End...");
		}
	}
}

class threadA extends Thread {

	public void run() {
		for (int i = 1; i <= 10; i++) {
			A.bf.append(1);
			try {
				sleep(10);
			} catch (InterruptedException e) {
				continue;
			}
		}

		System.out.println(A.bf.toString());
		A.callback();
	}
}

class threadB extends Thread {

	public void run() {
		for (int i = 1; i <= 10; i++) {
			A.bf.append(2);
			try {
				sleep(10);
			} catch (InterruptedException e) {
				continue;
			}
		}

		System.out.println(A.bf.toString());
		A.callback();
	}
}

```