我有一个ArrayList,我想用来容纳RaceCar对象,这些对象在执行完后立即扩展Thread类。名为Race的类使用RaceCar对象完成执行后调用的回调方法来处理此ArrayList。回调方法addFinisher(RaceCar finisher)将RaceCar对象添加到ArrayList。这应该给出线程完成执行的顺序。
我知道ArrayList不同步,因此不是线程安全的。我尝试使用Collections.synchronizedCollection(c Collection)方法,方法是传入新的ArrayList并将返回的Collection分配给ArrayList。但是,这给了我一个编译器错误:
Race.java:41: incompatible types
found : java.util.Collection
required: java.util.ArrayList
finishingOrder = Collections.synchronizedCollection(new ArrayList(numberOfRaceCars));
以下是相关代码:
public class Race implements RaceListener {
private Thread[] racers;
private ArrayList finishingOrder;
//Make an ArrayList to hold RaceCar objects to determine winners
finishingOrder = Collections.synchronizedCollection(new ArrayList(numberOfRaceCars));
//Fill array with RaceCar objects
for(int i=0; i<numberOfRaceCars; i++) {
racers[i] = new RaceCar(laps, inputs[i]);
//Add this as a RaceListener to each RaceCar
((RaceCar) racers[i]).addRaceListener(this);
}
//Implement the one method in the RaceListener interface
public void addFinisher(RaceCar finisher) {
finishingOrder.add(finisher);
}
我需要知道的是,我使用的是正确的方法吗?如果不正确,应该使用什么使我的代码具有线程安全性?谢谢您的帮助!
List
接口还不够完整,不足以在多线程中非常有用。)