Need a program to select InterruptedException

I go through kathy sierra SCJP 1.5 Chapter 9 (threads) and there it is referred to as:

Please note that the sleep () method can throw a valid InterruptedException (you usually know if this is possible, since the other thread must explicitly interrupt), so you must either throw an exception with a handle or declare it

I just need an example program to find out when this will happen (what can I run on my machine)?

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

Thanks at Advance

+5
source share
2 answers

Here is 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!");
        }
    }
}

Go through it:

  • , ,
  • ( )
  • , ( , )

, , , .

+19
public class SleepTest1 extends Thread {
@Override
public void run() {
    try {
        for (int i = 0; i < 5; i++) {
            System.out.println(Thread.currentThread().getName());
            Thread.sleep(1000);
            Thread.currentThread().interrupt();
        }

    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public static void main(String[] args) {
    SleepTest1 st1 = new SleepTest1();
    st1.start();
}

}

-1

All Articles