001package observer.seven; 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 IntObserver()); 008 Runnable r1 = new M(c); 009 Runnable r2 = new N(c); 010 for (int i=0; i<10000; i++) { 011 r1.run(); 012 r2.run(); 013 } 014 } 015} 016class IntObserver implements Observer { 017 private int numOps; 018 public void update(Observable o, Object arg) { 019 System.out.println (++numOps); 020 } 021} 022class Int extends Observable { 023 private int v; 024 public int get() { return v; } 025 public void inc() { v++; setChanged(); notifyObservers(); } 026 public void dec() { v--; setChanged(); notifyObservers(); } 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}