StringBuffer类及线程运行测试

虽然平时常常看到,毕竟很少用。居然在笔试的时候碰到了,而且还写得不好,真是惭愧...

StringBuffer类,主要是insert(int,String/int/Object/...)与append(String/int/Object/...)两个方法;
最后用.toString()方法把缓冲区内的数据转换为字符串表示。

StringBuffer类的引用:http://www.leftworld.net/online/j2sedoc/javaref/java.lang.stringbuffer_dsc.htm

据说是线程安全的,不过测试了下,发现这个概念理解有出入,貌似每次的结果是有差别的。


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了。不过这里主要是为了看下回调函数,有点锁的感觉。


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();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值