publicclassInterruptTestimplementsRunnable { publicstaticvoidmain(String[] args) { Threadthread=newThread(newInterruptTest()); thread.start(); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } thread.interrupt(); System.out.println("Thread state is set to interrupt"); }
@Override publicvoidrun() { while (true) { if (Thread.currentThread().isInterrupted()) { System.out.println("The thread is interrupted."); } else { System.out.println("The thread is NOT interrupted."); } } } }
…… The thread is NOT interrupted. The thread is NOT interrupted. Thread state is set to interrupt The thread is interrupted. The thread is interrupted.
Some operations. Thread state is set to interrupt Operations finished. Some operations. java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at test.InterruptTest.run(InterruptTest.java:21) at java.lang.Thread.run(Thread.java:748)
Some operations. Thread state is set to interrupt Operations finished. java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at test.InterruptTest.run(InterruptTest.java:24)