1 // Create many threads waiting on a monitor. Interrupt some of them. Do the
2 // others wake up correctly with notify() and/or notifyAll()?
3 // Origin: Bryce McKinlay <bryce@albatross.co.nz>
5 import java
.util
.Vector
;
7 class Waiter
extends Thread
11 boolean interrupted
= false;
12 boolean notified
= false;
14 Waiter (Object monitor
, int thread_num
)
16 this.monitor
= monitor
;
17 this.thread_num
= thread_num
;
22 synchronized (monitor
)
29 catch (InterruptedException x
)
38 public class Thread_Wait_2
40 static Vector threads
;
41 static Object monitor
= new Object();
43 static final int NUM_THREADS
= 10;
45 public static void main(String args
[])
55 // Interrupt a few threads...
56 Waiter i1
= (Waiter
) threads
.elementAt(3);
57 Waiter i2
= (Waiter
) threads
.elementAt(4);
58 Waiter i3
= (Waiter
) threads
.elementAt(9);
63 // Call notify the exact number of times required to wake the remaining
65 synchronized (monitor
)
67 for (int i
=0; i
< NUM_THREADS
-3 ; i
++)
76 // Repeat all the above, but use notifyAll() instead.
81 // Interrupt a few threads...
82 i1
= (Waiter
) threads
.elementAt(0);
83 i2
= (Waiter
) threads
.elementAt(1);
84 i3
= (Waiter
) threads
.elementAt(9);
89 // Call notifyAll to wake the remaining threads.
90 synchronized (monitor
)
99 catch (InterruptedException x
)
101 System
.out
.println (x
);
107 static void makeThreads()
109 threads
= new Vector(NUM_THREADS
);
111 for (int i
=0; i
< NUM_THREADS
; i
++)
113 Waiter w
= new Waiter(monitor
, i
);
115 threads
.addElement(w
);
119 static void joinAll()
123 for (int i
=0; i
< threads
.size(); i
++)
125 Thread t
= (Thread
) threads
.elementAt(i
);
129 catch (InterruptedException x
) {}
132 static void printStatus()
134 for (int i
=0; i
< threads
.size(); i
++)
136 Waiter w
= (Waiter
) threads
.elementAt(i
);
138 System
.out
.println (i
+ " interrupted.");
140 System
.out
.println (i
+ " notified.");