Java Reference
In-Depth Information
A simple method can be used for this purpose.
public
String cell(
int
i) {
return
cells[i];
}
The read and write commands issued by the CPU and the acknowledge
command from the RAM are messages that must be codified in a common
way shared by the two components. They are strings that are written to and
read from the command bus. It would be very easy to misspell one of the
commands exchanged between the CPU and the RAM. For instance, con-
sider the case if the CPU sends a
RAM-READ
instead of
RAM_READ
(a hyphen
character instead of an underscore). The RAM does not recognize the
command and stays idle, while the CPU sits waiting for an
ACK
that will
never arrive: a deadlock. In order to avoid this risk, command strings are
defined in a single place as constants in order to allow the compiler to catch
a spelling error.
final static
String RAM_READ
#
"RAM_READ";
final static
String RAM_WRITE
#
"RAM_WRITE";
final static
String ACK
#
"ACK";
The
execute()
method performs a single simulation step. It looks at the
command bus, if it contains the
RAM_READ
or
RAM_WRITE
command then
executes it and puts an
ACK
on the command bus.
boolean
execute() {
// Reads the command and the data from the bus
if
(bus.getCommand().equals(RAM_READ)) {
// Writes the content of the selected cell in the
// data bus
bus.setData(cells[bus.getAddress()]);
// Acknowledge the CPU of the command execution
bus.setCommand(ACK);
return true
;
}
else if
(bus.getCommand().equals(RAM_WRITE)) {
// Write the content of the data bus into the
// cell whose address is on the address bus
cells[bus.getAddress()]
#
bus.getData();
// Acknowledge the CPU of the command execution
bus.setCommand(ACK);
return true
;
}
return false
;
}
The association between the CPU and the bus is implemented as a private
attribute initialized in the constructor. The registers of the CPU can be