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