I'm not trying to fill the board with another of the same question, but I read about 15 solutions and nobody has quite the same issue. Here is the code I am looking at:
private AgentModel agent;
private UserModel user;
private int type;
public AgentThread(AgentModel agent, UserModel user, int type) {
this.agent = agent;
this.user = user;
this.type = type;
}
public void start() throws InterruptedException {
agent.setT(new Thread(this, agent.getID()));
agent.getT().start();
}
And a little bit down the way:
public void run() {
while (!agent.getT().isInterrupted()) {
agent.nextOP();
try {
if (agent.getOPS() > 0) {
agent.getT().sleep((long) (1000 / agent.getOPS()));
} else {
agent.getT().sleep(1000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
agent.getT().interrupt();
}
synchronized (user) {
agent.setState(agent.getT().getState().toString());
// System.out.println("Operations Completed: " +
// (1+agent.getOPCompleted()) );
if (type == 3) {
user.deposit(agent.getAmount(), Integer.valueOf(agent.getID()));
}
if (type == 4) {
user.withdraw(agent.getAmount(), Integer.valueOf(agent.getID()));
}
}
}
}
The agent object contains a thread that is started in the AgentThread start method. The AgentThread object takes in both the agent and the user and instances of their respective classes.
My problem is as follows: I'm setting the lock to be the instance of the UserModel class 'user'. The threads are supposed to either deposit or withdraw depending on their agent type.
When I execute agent.getT().getState()
, it always returns RUNNABLE no matter how many instances of AgentThread I have created. Each AgentThread is given a new agent and a new thread but the same User object. It seems as though the threads are never blocking each other.
I know they are influencing the same user instance because I can output the changes detected by my listener and it reflects all running threads and their interactions with that user instance.
Every time a thread is started it enters an "infinite" loop where the user instance has a deposit or a withdrawal. These actions happen every x seconds.