简体   繁体   English

独家访问方法/字段

[英]Exclusive access to method/field

In my application I have a class which has a variable which gets updated everytime a new event comes in: 在我的应用程序中,我有一个带有变量的类,该变量在每次出现新事件时都会更新:

class Logger{

  private String mVariable ="";

  public void onEvent(Event e) {
    //update mVariable here
  }

  public void log() {
     //write mVariable to file
  }
}

Now, I have another class which wants to trigger the Logger class to write the current value to a file. 现在,我还有另一个要触发Logger类将当前值写入文件的类。

class Trigger{

   //this is another event, not the event for which Logger is waiting for
   public void onEvent(Event e) {
      mLogger.log();
   }
}

How can I ensure that the Trigger class has exclusive access to the value of mVariable whenever it wants? 如何确保Trigger类在需要时可以独占访问mVariable的值? ie When the Trigger class calls the log method the value of mVariable should not be overridden by the Logger class of course. 即,当Trigger类调用log方法时, Logger类当然不应覆盖mVariable的值。

使两个方法synchronized然后调用lock()将锁定对onEvent()的访问

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

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