如何在程序中证明StringBuilder
不是线程安全的?
我尝试了以下代码,但它并没有起到作用:
public class Threadsafe {
public static void main(String[] args) throws InterruptedException {
long startdate = System.currentTimeMillis();
MyThread1 mt1 = new MyThread1();
Thread t = new Thread(mt1);
MyThread2 mt2 = new MyThread2();
Thread t0 = new Thread(mt2);
t.start();
t0.start();
t.join();
t0.join();
long enddate = System.currentTimeMillis();
long time = enddate - startdate;
System.out.println(time);
}
String str = "aamir";
StringBuilder sb = new StringBuilder(str);
public void updateme() {
sb.deleteCharAt(2);
System.out.println(sb.toString());
}
public void displayme() {
sb.append("b");
System.out.println(sb.toString());
}
}
class MyThread1 implements Runnable {
Threadsafe sf = new Threadsafe();
public void run() {
sf.updateme();
}
}
class MyThread2 implements Runnable {
Threadsafe sf = new Threadsafe();
public void run() {
sf.displayme();
}
}
Threadsafe sf = new Threadsafe()
(在您的两个线程类中)=> 这意味着,您的两个线程正在操作不同的Threadsafe
实例,因此是不同的StringBuilder
实例! - Seelenvirtuosecurl https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html | grep "not safe for use by multiple threads" && echo "Not thread safe"
的含义是:该文档记录了StringBuilder类不支持多线程使用。尽管实现可能已更改,变得支持多线程使用,但是不能保证其一定是线程安全的,因此不应该依赖它具有线程安全的属性。 - Andy Turner