对于下面的例子的对象:爪哇等待在另一个线程
public Car getCar(int id){
Car result= findCarInCache(id);
if (result==null){
// POINT A
return createCarWithId(id);
} else {
return result;
}
}
public Car findCarInCache(int id){
// Do something for find a car with this id in the cache
}
public void addToCache(Car car){
// Add the car to the cache
}
public Car createCarWithId(int id){
Thread.sleep(10000);
Car result= new Car(id);
addToCache(Car);
return result;
}
问题是当两个线程调用同时getCar(2)例如。然后两个线程都到达POINT A,并且生成Car#2的两个实例。我如何让第二个线程在POINT A处等待,直到第一个线程完成创建,然后在两个调用中返回相同的对象? (我在Android中这样做)
感谢
http://docs.oracle.com/javase/tutorial/essential/concurrency/。或者类似的,一本关于java的初学者书。如果你使用线程,你需要了解并发性 –