gpt4 book ai didi

java - 多个对象调用另一个方法方法

转载 作者:行者123 更新时间:2023-12-02 11:32:16 24 4
gpt4 key购买 nike

在我的系统中,飞机随机移动,当满足条件时,它们会向中心站发送文件,这意味着可能会发生某些飞机在该时间点发送文件的情况。

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());
}
}

问题:

  • 多个对象可以同时调用另一个方法吗?
  • 如果不,为什么不呢?

最佳答案

是的,可以同时调用 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() 使用所有局部变量并且不使用任何状态更改类级别变量,则无需处理并发。

关于java - 多个对象调用另一个方法方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49207755/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com