2019-03-04

StringBuffer是否真的线程安全的验证

为了验证StringBuffer是不是真的线程安全,我写了一个测试程序来验证,示例代码如下:

public class StringBudr {

    public static void main(String args[]) {
        StringBuffer buffer = new StringBuffer("");
        StringBuilder builder = new StringBuilder("");
        for (int i = 0; i < 1000; i++) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    buffer.append("a");
                    builder.append("b");
                }
            }).start();
        }
        System.out.println("buffer:" + buffer.length());
        System.out.println("builder:" + builder.length());
    }
}

某次执行结果如下:

buffer:997
builder:1000

这个执行结果和预期的可不一样啊,想了想,把线程数目调成20,并且把2个字符串的内容也打印出来

public class StringBudr {

    public static void main(String args[]) {
        StringBuffer buffer = new StringBuffer("");
        StringBuilder builder = new StringBuilder("");
        for (int i = 0; i < 20; i++) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    buffer.append("a");
                    builder.append("b");
                }
            }).start();
        }
        System.out.println("buffer:" + buffer.length());
        System.out.println(buffer.toString());
        System.out.println("builder:" + builder.length());
        System.out.println(builder.toString());
    }
}

再次执行

buffer:19
aaaaaaaaaaaaaaaaaaaa
builder:20
bbbbbbbbbbbbbbbbbbbb

打印的结果没有问题,但是程序显示的字符长度却不正确。想了想,可能是前面的线程没有执行完,修改下代码

public class StringBudr {

    public static void main(String args[]) {
        StringBuffer buffer = new StringBuffer("");
        StringBuilder builder = new StringBuilder("");
        for (int i = 0; i < 1000; i++) {
            new Thread(new Runnable() {

                @Override
                public void run() {
                    buffer.append("a");
                    builder.append("b");
                }
            }).start();
        }
        while (Thread.activeCount() > 1)
            Thread.yield();
        System.out.println("buffer:" + buffer.length());
        System.out.println("builder:" + builder.length());

改成这样之后,buffer和builder的长度打印出来都是1000了

你可能感兴趣的:(2019-03-04)