繁体   English   中英

多个对象调用另一个方法method

[英]Multiple objects calling another method method

在我的系统中,飞机随机移动,并在满足条件时将文件发送到中心站,这意味着某些飞机可能会在该时间点发送文件。

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()调用,则必须处理多线程方案。

PS :如果SingleCentralStation#sendDocument()使用所有局部变量并且不使用任何状态更改类级别变量,则无需处理并发。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM