]>
Commit | Line | Data |
---|---|---|
e8904f65 BM |
1 | // Create two threads waiting on a monitor. Interrupt one of them. Does the |
2 | // other wake up correctly? | |
3 | // Origin: Bryce McKinlay <bryce@albatross.co.nz> | |
4 | ||
5 | class Waiter extends Thread | |
6 | { | |
7 | Object monitor; | |
8 | int thread_num; | |
9 | boolean interrupted = false; | |
10 | boolean notified = false; | |
11 | ||
12 | Waiter (Object monitor, int thread_num) | |
13 | { | |
14 | this.monitor = monitor; | |
15 | this.thread_num = thread_num; | |
16 | } | |
17 | ||
18 | public void run() | |
19 | { | |
20 | synchronized (monitor) | |
21 | { | |
22 | System.out.println ("Thread waiting."); | |
23 | try | |
24 | { | |
25 | long start = System.currentTimeMillis(); | |
26 | monitor.wait(1000); | |
27 | long time = System.currentTimeMillis() - start; | |
28 | if (time > 990) | |
29 | System.out.println ("Error: wait on thread " + thread_num | |
30 | + " timed out."); | |
31 | else | |
32 | notified = true; | |
33 | } | |
34 | catch (InterruptedException x) | |
35 | { | |
36 | interrupted = true; | |
37 | } | |
38 | } | |
39 | ||
40 | } | |
41 | } | |
42 | ||
43 | public class Thread_Wait_Interrupt | |
44 | { | |
45 | public static void main(String args[]) | |
46 | { | |
47 | Object monitor = new Object(); | |
48 | Waiter w1 = new Waiter(monitor, 1); | |
49 | Waiter w2 = new Waiter(monitor, 2); | |
50 | w1.start(); | |
51 | w2.start(); | |
52 | try | |
53 | { | |
54 | Thread.sleep(250); | |
55 | ||
56 | synchronized (monitor) | |
57 | { | |
58 | w1.interrupt(); | |
59 | monitor.notify(); | |
60 | } | |
61 | ||
62 | w1.join(); | |
63 | w2.join(); | |
64 | System.out.println("join ok"); | |
65 | System.out.println("Thread 1 " + | |
66 | (w1.interrupted ? "interrupted ok" : "error")); | |
67 | System.out.println("Thread 2 " + | |
68 | (w2.notified ? "notified ok" : "error")); | |
69 | ||
70 | } | |
71 | catch (InterruptedException x) | |
72 | { | |
73 | System.out.println (x); | |
74 | } | |
75 | } | |
76 | } |