concurrency-problems

git clone git://git.codymlewis.com/concurrency-problems.git
Log | Files | Refs | README

Timer.java (1062B)


      1 /**
      2  * Timer - COMP2240
      3  * Keep time in a separate Thread
      4  *
      5  * @author Cody Lewis (c3283349)
      6  */
      7 
      8 public class Timer extends Thread {
      9     private int time;
     10     private boolean alive;
     11     /**
     12      * Amount of time (ms) for a single unit of sleep
     13      */
     14     public static final int QUANTUM = 100;
     15     public static final int EPSILON = 5;
     16 
     17     /**
     18      * Default constructor
     19      */
     20     public Timer() {
     21         time = 0;
     22         alive = true;
     23     }
     24 
     25     /**
     26      * Get the current time in quantums from this Thread starting
     27      *
     28      * @return time in quantums from this starting
     29      */
     30     public int getTime() {
     31         return time;
     32     }
     33 
     34     /**
     35      * Kill this timer
     36      */
     37     public void kill() {
     38         alive = false;
     39     }
     40 
     41     /**
     42      * Sleep for a quantum then iterate the time
     43      */
     44     public void run() {
     45         try {
     46             while(alive) {
     47                 Thread.sleep(Timer.QUANTUM);
     48                 time++;
     49             }
     50         } catch (Exception e) {
     51             System.out.format("Error: %s", e.getMessage());
     52         }
     53     }
     54 }