Java – sample programs are required to throw interruptedexception
•
Java
I'm going through Chapter 9 (threads) of Kathy Sierra scjp 1.5, which is mentioned:
I just need a sample program to know when it happens (I can run it on my machine)?
I searched with Google but couldn't find any sample code to test this feature
Thank you in advance
Solution
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!"); } } }
To complete it:
>Set a new thread, which will pause for a period of time, and then interrupt the main thread > start a new thread > long sleep (in the main thread) > print out a diagnostic method when we are interrupted (again, in the main thread)
Sleep in the main thread is not absolutely necessary, but it means that the main thread does start sleeping before it is interrupted
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码