1 // Create many threads waiting on a monitor. Interrupt some of them. Do the
2 // others wake up correctly with notify() and/or notifyAll()?
4 import java
.util
.Vector
;
6 class Waiter
extends Thread
10 boolean interrupted
= false;
11 boolean notified
= false;
13 Waiter (Object monitor
, int thread_num
)
15 this.monitor
= monitor
;
16 this.thread_num
= thread_num
;
21 synchronized (monitor
)
28 catch (InterruptedException x
)
37 public class Thread_Wait_2
39 static Vector threads
;
40 static Object monitor
= new Object();
42 static final int NUM_THREADS
= 10;
44 public static void main(String args
[])
54 // Interrupt a few threads...
55 Waiter i1
= (Waiter
) threads
.elementAt(3);
56 Waiter i2
= (Waiter
) threads
.elementAt(4);
57 Waiter i3
= (Waiter
) threads
.elementAt(9);
62 // Call notify the exact number of times required to wake the remaining
64 synchronized (monitor
)
66 for (int i
=0; i
< NUM_THREADS
-3 ; i
++)
75 // Repeat all the above, but use notifyAll() instead.
80 // Interrupt a few threads...
81 i1
= (Waiter
) threads
.elementAt(0);
82 i2
= (Waiter
) threads
.elementAt(1);
83 i3
= (Waiter
) threads
.elementAt(9);
88 // Call notifyAll to wake the remaining threads.
89 synchronized (monitor
)
98 catch (InterruptedException x
)
100 System
.out
.println (x
);
106 static void makeThreads()
108 threads
= new Vector(NUM_THREADS
);
110 for (int i
=0; i
< NUM_THREADS
; i
++)
112 Waiter w
= new Waiter(monitor
, i
);
114 threads
.addElement(w
);
118 static void joinAll()
122 for (int i
=0; i
< threads
.size(); i
++)
124 Thread t
= (Thread
) threads
.elementAt(i
);
128 catch (InterruptedException x
) {}
131 static void printStatus()
133 for (int i
=0; i
< threads
.size(); i
++)
135 Waiter w
= (Waiter
) threads
.elementAt(i
);
137 System
.out
.println (i
+ " interrupted.");
139 System
.out
.println (i
+ " notified.");