如何以编程方式证明 StringBuilder 不是线程安全的?
2022-08-31 22:41:15
如何以编程方式证明不是线程安全的?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();
}
}