我有一个发送 SNMP 命令并侦听陷阱的程序。
我的第一种方法是协调 SNMP 的发送。一旦他完成发送,我需要他等到他收到陷阱已收到的通知,这样他才能继续运行。现在,我正在尝试通过同步一个全局对象来做到这一点,但它不起作用,我不确定它是否是我的理想解决方案。
public synchronized int loginUser(ScopedPDU pdu) throws IOException
{
loginUserManager = new LoginUserManager();
pdu = buildPdu();
// send command
errorStatus = snmpManager.snmpSend(pdu);
if (errorStatus == SnmpManager.SNMP_PASS)
{
// Wait for traps
synchronized(syncObject)
{
// read global variable status to see if it's no longer in progress
while(status == TrapStatus.INPROGRESS)
{
try {
System.out.println("Waiting for login to be done");
syncObject.wait();
System.out.println("We received a notify");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} //(errorStatus == SnmpManager.SNMP_PASS)
else
{
return TrapStatus.FAIL;
}
System.out.println("Returning status");
return status;
}
我的第二种方法是接收陷阱(并在与第一种方法不同的线程上运行)并获得我想要的正确状态,但我无法通知另一个线程。
public synchronized void readTrap(Vector v)
{
Enumeration e = v.elements();
if(v.contains(PduTrap.UserLoginStatusTrap))
{
// gets status of login
status = loginUserManager.getStatus(e);
synchronized(syncObject)
{
// notify first method to read the new status
syncObject.notify();
}
}
}
status 和 SyncObject 是我试图在线程之间共享的全局类型。我在类构造函数中将状态初始化为 INPROGRESS。
private int status;
private Object syncObject;
有人可以告诉我为什么事情不正常,或者我是否完全以错误的方式解决这个问题?目前,我的 loginUser 方法没有被 readTrap 通知。谢谢