001package observer.six;
002import java.util.List;
003import java.util.ArrayList;
004
005public class Main {
006        public static void main(String[] argv) {
007                Int c = new Int();
008                c.addObserver(new IntObserver());
009                Runnable r1 = new M(c);
010                Runnable r2 = new N(c);
011                for (int i=0; i<10000; i++) {
012                        r1.run();
013                        r2.run();
014                }
015        }
016}
017
018interface Observer {
019        public void update();
020}
021
022class IntObserver implements Observer {
023        private int numOps;
024        public void update() {
025                System.out.println (++numOps);
026        }
027}
028class Int {
029        private List<Observer> observers = new ArrayList<Observer>();
030        private boolean changed = false;
031        public void addObserver(Observer o) {
032                observers.add(o);
033        }
034        private void setChanged() {
035                changed = true;
036        }
037        private void notifyObservers() {
038                if (changed) {
039                        for (Observer o : observers) {
040                                o.update();
041                        }
042                        changed = false;
043                }
044        }
045        private int v;
046        public int get() { return v; }
047        public void inc() { v++; setChanged(); notifyObservers(); }
048        public void dec() { v--; setChanged(); notifyObservers(); }
049}
050class M implements Runnable {
051        private Int c;
052        public M(Int c) { this.c = c; }
053        public void run() {
054                c.inc();
055                c.inc();
056                c.dec();
057        }
058}
059class N implements Runnable {
060        private Int c;
061        public N(Int c) { this.c = c; }
062        public void run() {
063                for (int i=0; i<50; i++) {
064                        if (i%3==0) {
065                                c.dec();
066                        } else {
067                                c.inc();
068                        }
069                }
070        }
071}