2003-12-26 Guilhem Lavaux <guilhem@kaffe.org>
[official-gcc.git] / libjava / testsuite / libjava.lang / Thread_Wait_2.java
bloba03cb943812a4dae1dcf0207e67e4bf68a71318a
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
9 Object monitor;
10 int thread_num;
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;
20 public void run()
22 synchronized (monitor)
24 try
26 monitor.wait();
27 notified = true;
29 catch (InterruptedException x)
31 interrupted = true;
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[])
49 try
51 makeThreads ();
53 Thread.sleep(250);
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);
59 i1.interrupt();
60 i2.interrupt();
61 i3.interrupt();
63 // Call notify the exact number of times required to wake the remaining
64 // threads.
65 synchronized (monitor)
67 for (int i=0; i < NUM_THREADS -3 ; i++)
69 monitor.notify ();
73 joinAll();
74 printStatus();
76 // Repeat all the above, but use notifyAll() instead.
77 makeThreads();
79 Thread.sleep(250);
81 // Interrupt a few threads...
82 i1 = (Waiter) threads.elementAt(0);
83 i2 = (Waiter) threads.elementAt(1);
84 i3 = (Waiter) threads.elementAt(9);
85 i1.interrupt();
86 i2.interrupt();
87 i3.interrupt();
89 // Call notifyAll to wake the remaining threads.
90 synchronized (monitor)
92 monitor.notifyAll ();
95 joinAll();
96 printStatus();
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);
114 w.start();
115 threads.addElement(w);
119 static void joinAll()
123 for (int i=0; i < threads.size(); i++)
125 Thread t = (Thread) threads.elementAt(i);
126 t.join();
129 catch (InterruptedException x) {}
132 static void printStatus()
134 for (int i=0; i < threads.size(); i++)
136 Waiter w = (Waiter) threads.elementAt(i);
137 if (w.interrupted)
138 System.out.println (i + " interrupted.");
139 if (w.notified)
140 System.out.println (i + " notified.");