在我的系统中,飞机随机移动,当条件满足时,它们会向中心站发送文件,这意味着某些飞机可能会在该时间点发送文件。
class SingleCentralStation{
public sendDocument(Document document){
//do something
}
}
class Spacecraft{
private SingleCentralStation singleCentralStation;
public Spacecraft(SingleCentralStation singleCentralStation){
this.singleCentralStation = singleCentralStation;
}
public sendDocumentToCentralStation(Document document){
singleCentralStation.sendDocument(document);
}
}
class App{
public static void main(String[] args) {
SingleCentralStation centralStation = new SingleCentralStation(); // singleton
Spacecraft spacecraft1 = new Spacecraft(centralStation);
Spacecraft spacecraft2 = new Spacecraft(centralStation);
Spacecraft spacecraft3 = new Spacecraft(centralStation);
Spacecraft spacecraft4 = new Spacecraft(centralStation);
Spacecraft spacecraft5 = new Spacecraft(centralStation);
// let's imagine that spacecrafts decide to send a document to central station all at the same point in time
spacecraft1.sendDocumentToCentralStation(new Document());
spacecraft2.sendDocumentToCentralStation(new Document());
spacecraft3.sendDocumentToCentralStation(new Document());
spacecraft4.sendDocumentToCentralStation(new Document());
spacecraft5.sendDocumentToCentralStation(new Document());
}
}
问题:
答案 0 :(得分:1)
是的,可以同时调用SingleCentralStation#sendDocument()
方法。你给出的例子
spacecraft1.sendDocumentToCentralStation(new Document());
spacecraft2.sendDocumentToCentralStation(new Document());
spacecraft3.sendDocumentToCentralStation(new Document());
spacecraft4.sendDocumentToCentralStation(new Document());
spacecraft5.sendDocumentToCentralStation(new Document());
这些实际上是一个接一个地执行的顺序调用。
如果要同时进行SingleCentralStation#sendDocument()
调用,则必须处理多线程方案。
P.S.
:如果SingleCentralStation#sendDocument()
使用所有局部变量并且没有使用任何状态更改类级别变量,则无需处理并发。