001package observer.eight;
002import java.util.Observer;
003import java.util.Observable;
004public class Main {
005        public static void main(String[] argv) {
006                Int c = new Int();
007                c.addObserver(new Observer() {
008                        private int numOps;
009                        public void update(Observable o, Object arg) {
010                                System.out.println (++numOps);
011                        }
012                });
013                Runnable r1 = new M(c);
014                Runnable r2 = new N(c);
015                for (int i=0; i<10000; i++) {
016                        r1.run();
017                        r2.run();
018                }
019        }
020}
021class Int extends Observable {
022        private int v;
023        public int get() { return v; }
024        public void inc() { v++; setChanged(); notifyObservers(); }
025        public void dec() { v--; setChanged(); notifyObservers(); }
026}
027class M implements Runnable {
028        private Int c;
029        public M(Int c) { this.c = c; }
030        public void run() {
031                c.inc();
032                c.inc();
033                c.dec();
034        }
035}
036class N implements Runnable {
037        private Int c;
038        public N(Int c) { this.c = c; }
039        public void run() {
040                for (int i=0; i<50; i++) {
041                        if (i%3==0) {
042                                c.dec();
043                        } else {
044                                c.inc();
045                        }
046                }
047        }
048}