gpt4 book ai didi

java - 实例变量赋值不粘

转载 作者:行者123 更新时间:2023-12-01 19:07:24 25 4
gpt4 key购买 nike

我有以下代码:

public class PatientAgent extends Agent {

private final String HYPHEN = "-";

private ArrayList<HashSet<Integer>> prefs;

private AID provider ;

private boolean hasAppointment;

private int appointmentNo;

@Override
protected void setup() {

hasAppointment = false;

appointmentNo = 0; // A value of zero means agent does not have any
// allocated appointments (yet)

initPrefs(getArguments());

System.out.println(prefs.toString());

// Build the description used as template for the subscription
DFAgentDescription template = new DFAgentDescription();
ServiceDescription templateSd = new ServiceDescription();
templateSd.setType("allocate-appointments");
template.addServices(templateSd);


SearchConstraints sc = new SearchConstraints();
// We want to receive 10 results at most
sc.setMaxResults(new Long(10));

addBehaviour(new SubscriptionInitiator(this, DFService.createSubscriptionMessage(this, getDefaultDF(), template, sc)) {
protected void handleInform(ACLMessage inform) {
System.out.println("Agent "+getLocalName()+": Notification received from DF");
try {
DFAgentDescription[] results = DFService.decodeNotification(inform.getContent());

if (results.length > 0) {

// Assume there is only one hospital agent
assert(results.length == 1);
DFAgentDescription dfd = results[0];


Iterator it = dfd.getAllServices();
while (it.hasNext()) {
ServiceDescription sd = (ServiceDescription) it.next();
if (sd.getType().equals("allocate-appointments")) {
provider = dfd.getName();
System.out.println("Allocate-appointments service found:");
System.out.println("- Service \""+sd.getName()+"\" provided by agent "+provider.getName());

}
}



}

}
catch (FIPAException fe) {
fe.printStackTrace();
}
}
} );


public AID getProvider() { return provider; }

我清楚地用该行初始化提供程序

   provider = dfd.getName();

但是行

       public AID getProvider() { return provider; }

返回 null,我不明白为什么。有人知道发生了什么事吗?

最佳答案

假设您正在执行赋值语句,请考虑以下事项:

  • getProvider() 是否在 handleInform 之前被调用?

  • handleInformgetProvider() 是否在单独的线程上调用,从而造成竞争或内存可见性问题?

  • handleInform 中赋值和使用 getProvider() 检索之间的某个时间,provider 变量是否被覆盖?

我想不出其他的了。您的变量范围看起来不错。您应该向 getProvider() 方法添加一条日志语句,以查看何时相对于 handleInform 调用它,并记录程序中可能覆盖变量的任何其他位置值。

关于java - 实例变量赋值不粘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9542067/

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