// ThreadInterruptionDemo.java class ThreadInterruptionDemo { public static void main(String [] args) { ThreadB thdb = new ThreadB(); thdb.setName ("B"); ThreadA thda = new ThreadA(thdb); thda.setName("A"); thdb.start(); thda.start(); } } class ThreadA extends Thread { private Thread thdOther; ThreadA(Thread thdOther) { this.thdOther = thdOther; } public void run() { int sleepTime = (int) (Math.random() * 10000); System.out.println( getName() + " sleeping for " + sleepTime + " milliseconds."); try { Thread.sleep(sleepTime); } catch (InterruptedException e) { } System.out.println( getName() + " waking up, interrupting other " + "thread and terminating."); thdOther.interrupt(); } } class ThreadB extends Thread { int count = 0; public void run() { while (!isInterrupted()) { try { Thread.sleep((int) (Math.random()*100 + 1)); } catch (InterruptedException e) { // Well, this thread has been interrupted. // By convention, let's clean up and terminate System.out.println( getName() + " about to terminate..."); // Because the boolean isInterrupted flag in thread B is clear, we call interrupt() // to set that flag. As a result, the next call to isInterrupted() // retrieves a true value, which causes the while loop to terminate. System.out.println("Here isInterrupted status of the thread " + getName() + " is " + isInterrupted() ); interrupt(); // re-assert the interrupt to make sure that // isInterrupted status is true: then our while-loop terminates } System.out.println( getName() + " " + count++); } } }