OSDN Git Service

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