【发布时间】:2017-05-02 09:48:04
【问题描述】:
有没有输出不是A/B/BC/AD(/是换行)的情况?第二个线程是否有可能在第一个线程之前开始?
public class JavaApplication6 extends Thread{
final StringBuffer sb1 = new StringBuffer();
final StringBuffer sb2 = new StringBuffer();
public static void main(String[] args) throws InterruptedException {
final JavaApplication6 h = new JavaApplication6();
new Thread(){
public void run(){
synchronized(this){
h.sb1.append("A");
h.sb2.append("B");
System.out.println(h.sb1);
System.out.println(h.sb2);
}
}
}.start();
new Thread(){
public void run(){
synchronized(this){
h.sb1.append("D");
h.sb2.append("C");
System.out.println(h.sb2);
System.out.println(h.sb1);
}
}
}.start();
}}
【问题讨论】:
标签: java multithreading thread-safety synchronized