1 package gov.nasa.jpf.jvm; 20 21 24 public class TestWait 25 { 26 boolean cond; 27 boolean done; 28 29 public static void main (String [] args) { 30 TestWait t = new TestWait(); 31 32 if (args.length > 0) { 33 for (int i = 0; i < args.length; i++) { 35 String func = args[i]; 36 37 if ("testSimpleWait".equals(func)) { 40 t.testSimpleWait(); 41 } else if ("testLoopedWait".equals(func)) { 42 t.testLoopedWait(); 43 } else if ("testInterruptedWait".equals(func)){ 44 t.testInterruptedWait(); 45 } else { 46 throw new IllegalArgumentException ("unknown test function"); 47 } 48 } 49 } else { 50 t.testSimpleWait(); 52 t.testLoopedWait(); 53 t.testInterruptedWait(); 54 } 55 } 56 57 public void testSimpleWait () { 58 Runnable notifier = new Runnable () { 59 public void run () { 60 synchronized (TestWait.this) { 61 System.out.println( "notifying"); 62 cond = true; 63 TestWait.this.notify(); 64 } 65 } 66 }; 67 68 Thread t = new Thread (notifier); 69 70 cond = false; 71 72 synchronized (this) { 73 t.start(); 74 75 try { 76 System.out.println("waiting"); 77 wait(); 78 System.out.println("notified"); 79 if (!cond) { 80 throw new RuntimeException ("'cond' not set, premature wait return"); 81 } 82 } catch (InterruptedException ix) { 83 } 84 } 85 } 86 87 public void testLoopedWait () { 88 Runnable notifier = new Runnable () { 89 public void run () { 90 while (!done) { 91 synchronized (TestWait.this) { 92 System.out.println( "notifying"); 93 cond = true; 94 TestWait.this.notify(); 95 } 96 } 97 } 98 }; 99 100 Thread t = new Thread (notifier); 101 102 cond = false; 103 done = false; 104 105 t.start(); 106 synchronized (this) { 107 for (int i=0; i<5; i++) { 108 try { 109 System.out.println("waiting " + i); 110 wait(); 111 System.out.println("notified " + i); 112 if (!cond) { 113 throw new RuntimeException ("'cond' not set, premature wait return"); 114 } 115 cond = false; 116 } catch (InterruptedException ix) {} 117 } 118 done = true; 119 } 120 } 121 122 public void testInterruptedWait () { 123 final Thread current = Thread.currentThread(); 124 125 Runnable notifier = new Runnable () { 126 public void run () { 127 synchronized (TestWait.this) { 128 System.out.println( "interrupting"); 129 cond = true; 130 current.interrupt(); 131 } 132 } 133 }; 134 Thread t = new Thread (notifier); 135 136 cond = false; 137 138 synchronized (this) { 139 t.start(); 140 141 try { 142 System.out.println("waiting"); 143 wait(); 144 System.out.println("notified"); 145 throw new RuntimeException ("notified, not interrupted"); 146 } catch (InterruptedException ix) { 147 if (!cond) { 148 throw new RuntimeException ("'cond' not set, premature wait return"); 149 } 150 } 151 } 152 } 153 } 154 155 | Popular Tags |