【发布时间】:2018-07-11 12:33:31
【问题描述】:
如何以编程方式证明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实例上运行! -
curl https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html | grep "not safe for use by multiple threads" && echo "Not thread safe"。它被记录为不是线程安全的。您可能无法证明它不是线程安全的,因为实现可能已经更改,因此它是;但是,您不应该依赖该属性,因为不能保证它会继续是线程安全的。 -
@MickMnemonic 可能是因为一些同事声称他们使用 StringBuilder 的多线程代码是完全安全的,而问题作者想证明他们是错误的。
-
一个主要警告:并发问题往往难以捉摸。即使该类不是线程安全的,您也可能不会遇到错误。有时很难找到此类错误。
标签: java multithreading thread-safety stringbuilder