Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Try creating a class Thermostat that encapsulate's your thermostat's state and behaviors. The trick is to use proper synchronization in order to maintain your program's invariants. Below you may find a <strong>sample</strong> implementation of a Thermostat class based on your requirements description, <strong>for illustration purposes</strong>. Notice how synchronization is used in order to preserve your invariants. Any method (such as up(int) and down(int) which both affect the current temperature) may be invoked concurrently by different threads, without race events or related hazards due to synchronization. </p> <p>Again, this is for illustration purposes only:</p> <pre><code>public final class Thermostat { // constant for maximum allowable temperature public static final int MAX_TEMP = 100; // the thermostat's current temperature private int temp = 0; // indicates if the boiler is on (true) or off (false) private boolean boilerStatus = false; public Thermostat() { } // Used to synchronize thread access to internal state (temp and // boilerStatus member variables. The monitor is private in order // for this class to encapsulate its synchronization policy. private final Object monitor = new Object(); // update the bolier's status to on (true) or off (false) public void setBoilerOn(boolean status) { synchronized (monitor) { this.boilerStatus = status; // if you block threads until boiler is switched on // (see below), this is the place to notify them... } } // returns true if the boiler is on, false otherwise public boolean isBoilerOn() { synchronized (monitor) { return this.boilerStatus; } } // increase the thermostat's temperature by the specified units // provided that the boiler has been set on public void up(int units) { synchronized (monitor) { // don't increase the temperature if the boiler // is not turned on... if (!isBoilerOn()) { // you could alternatively wait here if your // thread needs to block... return; } // increase the temperature if ((temp + units) &lt;= MAX_TEMP) { temp += units; } else { // TODO : handle incorect user input here... } } } // decrease the thermostat's temperature by the specified units // (negative values allowed) public void down(int units) { synchronized (monitor) { temp -= units; } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload