1 // Test interrupt() behaviour on a thread in wait(), sleep(), and spinning
3 // Origin: Bryce McKinlay <bryce@albatross.co.nz>
5 class Waiter
extends Thread
7 public synchronized void run()
9 System
.out
.println ("wait()");
13 System
.out
.println("Error: wait() completed normally.");
15 catch (InterruptedException x
)
17 if (isInterrupted() || interrupted())
18 System
.out
.println("Error: interrupt flag is still set.");
21 System
.out
.println("interrupted - ok");
25 class Sleeper
extends Thread
29 System
.out
.println ("sleep()");
33 System
.out
.println("Error: sleep() completed normally.");
35 catch (InterruptedException x
)
37 if (isInterrupted() || interrupted())
38 System
.out
.println("Error: interrupt flag is still set.");
40 System
.out
.println("interrupted - ok");
45 class Looper
extends Thread
47 // Return the number of Thread.yield()s we can do in 500ms.
48 static long calibrate ()
52 for (int tries
= 0; tries
< 40; tries
++)
54 long t
= System
.currentTimeMillis();
55 for (long n
= 0; n
< i
; n
++)
57 long t_prime
= System
.currentTimeMillis();
58 if (t_prime
- t
> 500)
62 // We have no system clock. Give up.
63 throw new RuntimeException ("We have no system clock.");
66 static long yields
= calibrate ();
70 System
.out
.println ("Busy waiting");
73 for (long i
=0; i
< yields
; i
++)
84 System
.out
.println ("interrupted - ok");
85 if (isInterrupted () || interrupted ())
86 System
.out
.println("Error: interrupt flag is still set.");
89 System
.out
.println ("Error: Busy wait was not interrupted.");
94 class Joiner
extends Thread
98 System
.out
.println("join()");
102 System
.out
.println("Error: join() completed normally??!");
104 catch (InterruptedException x
)
106 if (isInterrupted() || interrupted())
107 System
.out
.println("Error: interrupt flag is still set.");
109 System
.out
.println("interrupted - ok");
115 public class Thread_Interrupt
117 public static void main(String args
[])
119 Waiter w
= new Waiter();
121 sleep_and_interrupt (w
);
123 Sleeper s
= new Sleeper();
125 sleep_and_interrupt (s
);
127 Looper l
= new Looper ();
129 sleep_and_interrupt (l
);
131 Joiner j
= new Joiner ();
133 sleep_and_interrupt (j
);
136 public static void sleep_and_interrupt(Thread t
)
142 long t1
= System
.currentTimeMillis();
144 long time
= System
.currentTimeMillis() - t1
;
147 System
.out
.println ("Error: join() from main thread timed out");
150 catch (InterruptedException x
)
152 System
.out
.println("Error: main thread interrupted.");