/Users/lyon/j4p/src/bookExamples/ch13Threads/fsm/ObservableClock.java

1    /** 
2     * Created by IntelliJ IDEA. 
3     * User: dlyon 
4     * Date: Feb 4, 2004 
5     * Time: 4:31:18 PM 
6     * To change this template use Options | File Templates. 
7     */ 
8    package bookExamples.ch13Threads.fsm; 
9     
10   import java.util.Observable; 
11   import java.util.Observer; 
12    
13   public class ObservableClock extends Observable 
14           implements Runnable { 
15       Thread t = new Thread(this); 
16       private long milliseconds = 1000; 
17    
18       public ObservableClock(long milliseconds) { 
19           this.milliseconds = milliseconds; 
20           t.start(); 
21       } 
22    
23       public void run() { 
24           while (true) { 
25               try { 
26                   this.setChanged(); 
27                   this.notifyObservers(); 
28                   Thread.sleep(milliseconds); 
29               } catch (InterruptedException e) { 
30                   e.printStackTrace(); 
31               } 
32           } 
33       } 
34    
35       public static void main(String args[]) { 
36           ObservableClock oc = new ObservableClock(1000); 
37           Observer o = new Observer() { 
38               public void update(Observable obs, Object obj) { 
39                   System.out.println(obs); 
40               } 
41    
42           }; 
43           oc.addObserver(o); 
44       } 
45   } 
46