1 // Test that monitor locks work and are recursive. 2 // Origin: Bryce McKinlay <bryce@albatross.co.nz> 3 4 class T implements Runnable 5 { 6 public int count = 0; 7 Counter c; 8 T(Counter c)9 public T (Counter c) 10 { 11 this.c = c; 12 } 13 run()14 public void run() 15 { 16 while (true) 17 { 18 // NOTE: double-synchronization here. 19 synchronized (c) 20 { 21 if (c.getCount() <= 100000) 22 count++; 23 else 24 break; 25 } 26 } 27 } 28 } 29 30 class Counter 31 { 32 int i = 0; getCount()33 public synchronized int getCount () 34 { 35 return ++i; 36 } 37 } 38 39 public class Thread_Monitor 40 { main(String args[])41 public static void main(String args[]) 42 { 43 Counter c = new Counter(); 44 T t1 = new T(c); 45 T t2 = new T(c); 46 47 Thread th1 = new Thread(t1); 48 Thread th2 = new Thread(t2); 49 th1.start(); 50 th2.start(); 51 try 52 { 53 th1.join(); 54 th2.join(); 55 } 56 catch (InterruptedException x) 57 { 58 System.out.println("failed: Interrupted"); 59 } 60 if (t1.count + t2.count == 100000) 61 System.out.println ("ok"); 62 else 63 System.out.println ("failed: total count incorrect"); 64 } 65 } 66