Running
[Agent practical 10 of 9]


So, we want to set up our model so that it is run from within a separate thread from the main or EDT, where it can add events one at a time to the EDT, allowing the system to interleave user events into the event queue.


To do this, in our actionPerformed() we've changed:

runAgents();
saveMenuItem.setEnabled(true);

to:

Thread tt = new Thread(new Runnable() {
   public void run() {
      runAgents();
   }});

tt.start();
saveMenuItem.setEnabled(true);

This, again, uses an anonymous inner class, this time to set up a new Runnable object. Runnable is a class that encapsulates behaviour you want to run in a thread. To run one, you pass the Runnable into a Thread constructor, and then call the Thread's start() method. This, in turn, calls the Runnable's run() method. The Runnable object's behaviour is enacted within a separate processing thread. (the alternative method of using Threads is to extend them).

That's it! If you now run the model with the two new files, you'll see that our yellow "protector" agent responds to control by the arrow keys on the keyboard.


Obviously there's nothing to stop you adding additional listeners for mouse control etc.; for example, you might want to use the mouse to click on agents and add/subtract them, or change their behaviour so they are controlled by the keyboard.


Finally, I'd note that there are alternative architectures for this kind of thing. One, which you can find outlined in the Java Cookbook book, is to have each agent as an AWT Component that draws itself, which you add to a Panel on the GUI (in our case this would also contain the Canvas for drawing the Environment). Another is to have each agent run in its own thread (as mentioned above), and, indeed, one might combine both approaches. Each has its own advantages and disadvantages in terms of inter-agent communication and display, however, the method above is relatively simple to implement, while still allowing some parallelisation of the GUI-less version of the model and a relatively good speed.