为什么下面的代码只输出 3Thread-0
行,却输出了 6 行Thread-1
?
public class NameList{
private List names = new ArrayList();
public synchronized void addName(String name){
names.add(name);
}
public synchronized void print(){
for (int i = 0; i < names.size(); i++) {
System.out.print(names.get(i)+" ");
System.out.println(Thread.currentThread().getName());
}
}
public static void main(String args[]){
final NameList nl = new NameList();
for (int i = 0; i <2; i++) {
new Thread(){
public void run(){
nl.addName("A");
nl.addName("B");
nl.addName("C");
nl.print();
}
}.start();
}
}
}
输出:
A Thread-1
B Thread-1
C Thread-1
A Thread-0
B Thread-0
C Thread-0
A Thread-0
B Thread-0
C Thread-0