The Java Program: Interrupt.java
1
2
3 public class Interrupt extends Thread {
4 private int maxcount, current=0;
5
6 Interrupt (int maxcount) { this.maxcount = maxcount; }
7
8 public int getCount () { return current; }
9 public String toString () { return (getName()+" at "+getCount()); }
10
11 public void killLetDie () { interrupt(); Thread.yield(); }
12 public void killAndBlock () throws InterruptedException {
13 interrupt(); join();
14 }
15
16 public void run () {
17 try {
18 while (!isInterrupted() && current<maxcount) {
19 Thread.sleep ((int)(Math.random() * 300));
20 current++;
21 System.out.println (this);
22 }
23 if (current>=maxcount) {
24 System.out.println ("DONE! " + this);
25 } else {
26
27 System.out.println ("Loop interrupted! " + this);
28 }
29 } catch (InterruptedException e) {
30 final String x = isInterrupted()?"T":"F";
31 System.out.println ("Sleep interrupted ("+x+")! " + this);
32 }
33 }
34
35 public static void main (String args[]) throws InterruptedException {
36 Interrupt [] handle = new Interrupt [args.length];
37 for (int i=0; i<args.length; i++) {
38 handle[i] = new Interrupt (Integer.parseInt(args[i]));
39 handle[i].start();
40 }
41 Thread.sleep (1000);
42 for (int i=0; i<handle.length; i++) {
43 System.out.println ("Killing " + handle[i]);
44 handle[i].killAndBlock();
45 System.out.println ("Killed " + handle[i]);
46 }
47 }
48 }