我想知道 StringBuilder 和 StringBuffer 类及其实际用途之间的区别。因此,我编写了 2 个代码片段,其中我同时生成了 3 个线程,这些线程使用了 StringBuilder 和 StringBuffer 对象。
当我运行代码时,我希望所有 3 个线程在 StringBuilder 的情况下同时运行,在 StringBuffer 的情况下以同步的方式运行。但在这两种情况下,它们都以同步方式运行。那么StringBuffer类有什么用呢?:confused:
(对于 String 对象,所有 3 个线程同时运行)。我将分享代码片段供您参考。如果我对多线程本身的概念理解有误,也请纠正我。请同时更正代码。
// StringBuilder...
public class MultiTread implements Runnable{
private StringBuilder name;
public MultiTread(StringBuilder string){
name=string;
}
public void run(){
for(int i=0; i<=10; i++){
System.out.println(name.append(i));
}
}
public static void main(String[] args){
Thread th = new Thread(new MultiTread(new StringBuilder("thread1:")));
Thread th1 = new Thread(new MultiTread(new StringBuilder("thread2:")));
Thread th2 = new Thread(new MultiTread(new StringBuilder("thread3:")));
th.start();
th1.start();
th2.start();
}
}
..................
//StringBuffer...
public class MultiTreadBuf implements Runnable{
private StringBuffer name;
public MultiTreadBuf(StringBuffer string){
name=string;
}
public void run(){
for(int i=0; i<=10; i++){
System.out.println(name.append(i));
}
}
public static void main(String[] args){
Thread th = new Thread(new MultiTreadBuf(new StringBuffer("thread1:")));
Thread th1 = new Thread(new MultiTreadBuf(new StringBuffer("thread2:")));
Thread th2 = new Thread(new MultiTreadBuf(new StringBuffer("thread3:")));
th.start();
th1.start();
th2.start();
}
}
........
//String....
public class MuiltiTreadStr implements Runnable{
private String name;
public MuiltiTreadStr(String string){
name=string;
}
public void run(){
for(int i=0; i<=10; i++){
System.out.println(name+i);
}
}
public static void main(String[] args){
System.out.println("main begins...");
Thread th = new Thread(new MuiltiTreadStr("thread1:"));
Thread th1 = new Thread(new MuiltiTreadStr("thread2:"));
Thread th2 = new Thread(new MuiltiTreadStr("thread3:"));
System.out.println("spawning 3 threads...");
th.start();
th1.start();
th2.start();
System.out.println("main ends...");
}
}