爲什麼下面的代碼有Thread-0
輸出6行,當Thread-1
只輸出3?我的java線程代碼不會做我想要的
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