views:

52

answers:

1

Hi All

I am going through the kathy sierra SCJP 1.5 Chapter 9(threads) and there it is mentioned as:

Notice that the sleep() method can throw a checked InterruptedException (you'll usually know if that is a possibility, since another thread has to explicitly do the interrupting), so you must acknowledge the exception with a handle or declare

I just need a sample program to know when it happens (which i can run on my machine)?

I googled but could not find any sample code to test this functionality..

Thanks in Advance

+9  A: 

Here's an example:

public class Test
{
    public static void main (String[] args)
    {
        final Thread mainThread = Thread.currentThread();

        Thread interruptingThread = new Thread(new Runnable() {
            @Override public void run() {
                // Let the main thread start to sleep
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                mainThread.interrupt();
            }
        });

        interruptingThread.start();

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            System.out.println("I was interrupted!");
        }
    }
}

To walk through it:

  • Set up a new thread which will sleep for a short time, then interrupt the main thread
  • Start that new thread
  • Sleep for a long-ish time (in the main thread)
  • Print out a diagnostic method when we're interrupted (again, in the main thread)

The sleep in the main thread isn't strictly necessary, but it means that the main thread does get to really start sleeping before it's interrupted.

Jon Skeet
Thanks jon for your prompt answer..Just curious to know is there any way, through which we can cause interruptedexception,other than interrupt method??
javanoob
@javanoob: Not that I'm aware of... some other method can call `interrupt()` of course, so it may not be apparent to your code that `interrupt()` has been called, but that's basically how you interrupt the thread.
Jon Skeet